Skip to content
TypeScript·Intermediate·Coding·1 min read

What is a generic constraint?

Short interview answer

A constraint such as T extends { id: string } limits accepted types to those with required capabilities while retaining the caller's more specific type. It should state only what the implementation actually needs.

Example

TypeScript
function byId<T extends { id: string }>(items: T[], id: string) {  return items.find((item) => item.id === id); // .id is guaranteed}

Key takeaway

Explain the underlying mental model clearly, then support it with a concrete example and its trade-offs.

← Back to Generics

Related questions