What are generic constraints in TypeScript?

Why Interviewers Ask This

This is a classic screening question for TypeScript roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.

Answer

Generic constraints restrict what types can be used as type arguments using the extends keyword. Without constraints, a generic type parameter can be any type. With a constraint, you specify a minimum structure the type must have: function getLength<T extends { length: number }>(arg: T): number { return arg.length; }T must have a length property; this accepts strings, arrays, and any other type with length, but not numbers. Extend an interface: function processUser<T extends User>(user: T): T { ... }. Use keyof constraint for type-safe property access: function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; }. Constraints can reference other type parameters: function copyProps<S, D extends S>(source: S, dest: D): D { ... }. Constraints let you write flexible, reusable code while still accessing specific members of the generic type safely.

Pro Tip

Back up your answer with a specific project or situation. Saying 'In my last TypeScript project, I used this when...' immediately makes your answer more credible and memorable.