Skip to main content
Admin Panel
SC
Published
1 min read
259 words
Save
Publish
## Beyond the Basics If you've ever written `Array<T>` or `Promise<T>`, you've used generics. But TypeScript's type system offers far more powerful patterns that can make your code dramatically safer and more expressive. ## Pattern 1: Constrained Generics Constrain your type parameters to ensure they have the properties you need: ```typescript function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key] } const user = { name: "Sarah", age: 28 } const name = getProperty(user, "name") // type: string const age = getProperty(user, "age") // type: number ``` ## Pattern 2: Generic React Components Build type-safe, reusable UI components: ```tsx interface DataTableProps<T> { data: T[] columns: Column<T>[] onRowClick?: (item: T) => void } export function DataTable<T>({ data, columns, onRowClick }: DataTableProps<T>) { return ( <table> {data.map((item, i) => ( <tr key={i} onClick={() => onRowClick?.(item)}> {columns.map((col) => ( <td key={col.key}>{col.render(item)}</td> ))} </tr> ))} </table> ) } ``` > **Tip:** Generic components preserve type information through the entire chain — from data to event handlers. ## Pattern 3: Builder Pattern with Generics Create fluent APIs that accumulate type information: ```typescript class QueryBuilder<T extends Record<string, unknown>> { where<K extends keyof T>(key: K, value: T[K]): this { // implementation return this } } ``` ## Pattern 4: Mapped Types Transform types systematically: ```typescript type ReadOnly<T> = { readonly [K in keyof T]: T[K] } type Optional<T> = { [K in keyof T]?: T[K] } type Nullable<T> = { [K in keyof T]: T[K] | null } ``` These patterns compose beautifully and form the foundation of most TypeScript utility libraries.