TypeScript Master (50 Qs)•Part 1: Basic & Foundational TypeScript (Junior / Entry-Level)
How do Generic Constraints (`extends`) work?
junior LevelCode ExampleTypeScript
In Simple Words:
By default, generic <T> can be anything. Using T extends Shape constrains T to types that contain specific required properties:
typescript
interface HasLength {
length: number;
}
function logLength<T extends HasLength>(item: T): number {
return item.length;
}
logLength("hello"); // Valid (string has .length)
logLength([1, 2, 3]); // Valid (array has .length)
// logLength(123); // Error: Argument of type 'number' is not assignable to 'HasLength'