How do generics work in TypeScript?
Generics let you write reusable code that works with any type while still being type-safe like a type parameter you fill in at the call site.
TypeScript
Overview
Generics are TypeScript's way of writing code that works with multiple types without losing type information. Instead of using `any`, you use a type parameter (e.g. `<T>`) that is filled in when the function or class is used.
Key Points
- •Type parameters are written in `<>`: `function identity<T>(value: T): T`.
- •TypeScript can often infer the type parameter from the argument no need to write it explicitly.
- •Constraints with `extends` limit what types are accepted: `<T extends object>`.
- •Multiple type parameters are allowed: `<K, V>` for a map-like type.
- •Generic interfaces, classes, and type aliases follow the same pattern as generic functions.
Examples
Generic identity function
typescriptfunction identity<T>(value: T): T {
return value;
}
const n = identity(42); // T inferred as number
const s = identity("hello"); // T inferred as string
const explicit = identity<boolean>(true);Generic array utility
typescriptfunction first<T>(arr: T[]): T | undefined {
return arr[0];
}
const num = first([1, 2, 3]); // number | undefined
const word = first(['a', 'b']); // string | undefinedConstrained generics
typescriptfunction getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { name: 'Alice', age: 30 };
const name = getProperty(user, 'name'); // string
// getProperty(user, 'foo'); // Error: 'foo' not in userGeneric React component (common pattern)
typescriptinterface ListProps<T> {
items: T[];
renderItem: (item: T) => React.ReactNode;
}
function List<T>({ items, renderItem }: ListProps<T>) {
return <ul>{items.map(renderItem)}</ul>;
}Pro Tip
Start with a concrete type (`string`, `User`) and only introduce a generic when you genuinely need the function to work with multiple types. Premature generics make code harder to read without adding real flexibility.