Q19: How do Generic Constraints using the `extends` keyword work?

Difficulty:MediumTopic:Generics

Generic Constraints restrict the set of types acceptable by a generic parameter using the <T extends Boundary> syntax. This ensures the passed type satisfies specific structural requirements.

Constraining Generics to Objects with Length
interface Lengthwise {
  length: number;
}

function logLength<T extends Lengthwise>(arg: T): T {
  console.log(arg.length); // Guaranteed to exist
  return arg;
}

logLength("hello"); // Valid (strings have length)
logLength([1, 2, 3]); // Valid (arrays have length)
// logLength(123);   // Error: number doesn't have a 'length' property
💡 T extends Lengthwise guarantees that any type passed into T possesses a numeric length property.
Key Takeaways
  • Use extends to enforce required structural properties on generic type arguments.