Generic Constraints
ELI5 — The Vibe Check
Generic constraints are like telling a restaurant 'I'll eat anything... as long as it has cheese.' You keep the flexibility of generics but add rules about what types are allowed in. TypeScript respects the rules and blocks anything that doesn't qualify.
Real Talk
TypeScript's mechanism for restricting generic type parameters using the 'extends' keyword. Constraints ensure that generic types meet certain structural requirements, enabling safe access to properties and methods while maintaining type flexibility.
Show Me The Code
interface HasId {
id: number;
}
function findById<T extends HasId>(items: T[], id: number): T | undefined {
return items.find(item => item.id === id);
}
// Works with any type that has an 'id' property
findById([{ id: 1, name: 'Alice' }], 1);
When You'll Hear This
"Add a generic constraint so the function only accepts objects with an id field." / "T extends Record<string, unknown> ensures the generic is always an object."
Related Terms
Generic
A generic is like a recipe that works for any ingredient.
Interface
An interface is like a job description. It says 'whatever fills this role must be able to do X, Y, and Z' without caring how they do it.
TypeScript
TypeScript is JavaScript with a strict parent watching over it.
Utility Types
Utility types are TypeScript's built-in type transformers — like Instagram filters but for your interfaces.