Generics & Type Parameters
Generics allow you to write reusable functions, interfaces, and classes that operate over variable types while preserving complete type safety. Instead of relying on any (which disables type checking), generics use type parameters (e.g., <T>) that TypeScript infers or receives from callers.
Type parameters can be restricted using generic constraints (<T extends HasId>). Constraints guarantee that whatever argument type a caller passes, it must satisfy specific structural requirements (such as possessing an id property).
Exercise
Write a generic wrapper function createApiResponse<T>(data: T) that returns { data: T; status: number; timestamp: string }.
Check your understanding
Why is a generic function better than using any?Show answerHide answer
Answer
Generics preserve type relationships between inputs and output return values, keeping full autocomplete and type-checking intact.What does the extends keyword do inside generic parameter angle brackets <T extends Lengthwise>?Show answerHide answer
Answer
It places a constraint on T, enforcing that passed arguments must have all properties defined in Lengthwise.