TypeScript · Types that pay for themselves
What are generic constraints?
Short answer
A generic constraint uses extends to require that a type argument has certain members. It lets the implementation use those members safely while still accepting many concrete types.
Without a constraint, a generic type parameter could be anything, so the implementation cannot safely access properties. A constraint narrows the set of allowed type arguments. The compiler then permits operations guaranteed by the constraint and rejects callers that do not satisfy it.
function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
return items.map((item) => item[key]);
}
const names = pluck(
[{ name: "Asha" }, { name: "Ravi" }],
"name",
);Common constraint shapes
- T extends { id: string } requires an id property
- K extends keyof T restricts a key to properties of T
- T extends string restricts a type to string-like values
- T extends (...args: never[]) => unknown restricts a callable type
- A default type parameter can provide a fallback when inference fails
Constraints are checked at the call site, not at runtime. They improve the API but do not validate values. If the constraint says an object has an id, a value cast into that type can still be missing it at runtime.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What does K extends keyof T guarantee?
- 2Can a generic have both a constraint and a default?
- 3How is a constraint different from an intersection?
- 4What happens when a caller does not satisfy a constraint?
Say it in the interview
A constraint uses extends to say a type argument must have certain capabilities. For pluck, K extends keyof T means the key must actually exist on T, so the return type T[K] is precise. That gives callers safety without giving up generics. I use constraints whenever the implementation needs to access a property or call a method on the generic value.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live TypeScript mock interview and get scored feedback on depth, clarity and confidence.