Back to all posts
Mastering TypeScript: Advanced Types and Techniques
2023-06-30
TypeScript
TypeScript is a powerful superset of JavaScript that adds optional static typing and other features. In this post, we'll explore some of the more advanced types and techniques that TypeScript offers.
Union Types:
Union types allow a value to be one of several types. For example:
let result: number | string; result = 10; // OK result = "hello"; // Also OK
Conditional Types:
Conditional types select one of two possible types based on a condition:
type CheckNumber<T> = T extends number ? "Is a number" : "Not a number"; type Result = CheckNumber<5>; // "Is a number"
Mapped Types:
Mapped types allow you to create new types based on old ones:
type Readonly<T> = { readonly [P in keyof T]: T[P]; }; type Person = { name: string; age: number }; type ReadonlyPerson = Readonly<Person>;
Utility Types:
TypeScript provides several utility types to facilitate common type transformations:
type Partial<T> = { [P in keyof T]?: T[P] }; type Required<T> = { [P in keyof T]-?: T[P] }; type Pick<T, K extends keyof T> = { [P in K]: T[P] };
By mastering these advanced TypeScript features, you can write more robust and maintainable code, catching more errors at compile-time and improving your overall development experience.