Advanced TypeScript Types
TypeScript's type system is incredibly powerful. Let's explore some advanced patterns.
Conditional Types
type IsString = T extends string ? true : false;type A = IsString<"hello">; // true
type B = IsString<42>; // false
// Practical example: Extract return type
type ReturnType = T extends (...args: any[]) => infer R ? R : never;
function greet(): string {
return "Hello";
}
type GreetReturn = ReturnType; // string
Mapped Types
type Readonly = {
readonly [P in keyof T]: T[P];
};type Optional = {
[P in keyof T]?: T[P];
};
type Nullable = {
[P in keyof T]: T[P] | null;
};
interface User {
id: number;
name: string;
email: string;
}
type ReadonlyUser = Readonly;
type OptionalUser = Optional;
Template Literal Types
type EventName = "click" | "focus" | "blur";
type EventHandler = \on\${Capitalize}\ ;
// "onClick" | "onFocus" | "onBlur"type HTTPMethod = "GET" | "POST" | "PUT" | "DELETE";
type Endpoint = \/api/\${string}\;
type APIRoute = \\${HTTPMethod} \${Endpoint}\;
Utility Types
// Pick specific properties
type UserPreview = Pick;// Omit specific properties
type UserWithoutEmail = Omit;
// Make all properties required
type RequiredUser = Required;
// Extract and Exclude
type T1 = Extract<"a" | "b" | "c", "a" | "f">; // "a"
type T2 = Exclude<"a" | "b" | "c", "a">; // "b" | "c"