What are generic constraints in TypeScript?
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.