ProgrammingAdvanced
20 min readNov 5, 2024
TypeScript Advanced Types and Patterns
Deep dive into TypeScript advanced types including generics, conditional types, mapped types, and utility types.
R
Rithy Tep
Author
Introduction
Master advanced TypeScript features to write more type-safe and maintainable code.
1. Generics
Generic Functions
function identity<T>(value: T): T { return value } // Usage const num = identity<number>(42) const str = identity<string>("hello")
Generic Constraints
interface HasId { id: number } function findById<T extends HasId>(items: T[], id: number): T | undefined { return items.find(item => item.id === id) }
2. Conditional Types
type IsString<T> = T extends string ? true : false type A = IsString<string> // true type B = IsString<number> // false // Practical example type ApiResponse<T> = T extends { error: string } ? { success: false; error: string } : { success: true; data: T }
3. Mapped Types
type Readonly<T> = { readonly [P in keyof T]: T[P] } type Partial<T> = { [P in keyof T]?: T[P] } interface User { id: number name: string email: string } type ReadonlyUser = Readonly<User> type PartialUser = Partial<User>
4. Utility Types
// Pick type UserPreview = Pick<User, 'id' | 'name'> // Omit type UserWithoutEmail = Omit<User, 'email'> // Record type UserRoles = Record<string, 'admin' | 'user' | 'guest'> // ReturnType function getUser() { return { id: 1, name: 'John' } } type User = ReturnType<typeof getUser>
5. Template Literal Types
type EventName = 'click' | 'scroll' | 'mousemove' type HandlerName = `on${Capitalize<EventName>}` // Result: "onClick" | "onScroll" | "onMousemove"
Conclusion
These advanced TypeScript features help you write more robust and type-safe code.
#TypeScript#JavaScript#Types#Advanced