Generics
A generic is a recipe that works for any food.
You write one function or type that works with many types.
You still keep safety.
Instead of hard coding string or number, you add a type slot like T.
Generic functions
Declare type slots in angle brackets.
Example: function first<T>(items: T[]): T | undefined.
T is a placeholder name. You can pick other letters too.
TypeScript often guesses T from the arguments.
Constraints with extends
Sometimes T must have certain properties.
A constraint is a rule that T must follow.
Limit it with extends so you can safely use those members.
Generic interfaces and types
Boxes, responses, and lists are classic generic shapes.
Parameterize the payload.
Parameterize means leave a blank for the inner type.
Then one ApiResponse works for users, products, and more.
Default type parameters
You can give a type parameter a default.
Callers may skip it when the common case is enough.
Multiple type parameters
You can use more than one slot.
Name them clearly when T alone feels vague.
Reach for generics when you would otherwise copy the same logic for different types.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.