Generics let you write components that work over many types without losing type safety:
function identity<T>(value: T): T {
return value;
}
const num = identity(42); // T is number
const str = identity("hello"); // T is stringA type parameter like T is a placeholder for a concrete type that callers supply or TypeScript infers.
Key generic patterns:
Constraints – Require certain properties:
function getLength<T extends { length: number }>(value: T) {
return value.length; // Safe! We know T has length
}Related type parameters – Link keys to objects:
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key]; // Return type matches the property type
}Generic types and classes:
type Box<T> = { value: T };
class Stack<T> { /* ... */ }In this category, you'll:
extends to require specific propertieskeyof and indexed access for safe property lookupsNote: Type arguments are erased at runtime, so implementations rely on normal JavaScript while types keep the API safe.