GenericsLesson 4.2
Generic constraints in TypeScript using extends
extends constraint, constraining to interface, keyof constraint, multiple constraints, why unconstrained generics fail
Why constraints are needed
An unconstrained T cannot access any properties โ TypeScript does not know what T looks like:
function getName(obj: T): string {
return obj.name; // Error: Property 'name' does not exist on type 'T'
}Add a constraint with extends:
function getName(obj: T): string {
return obj.name; // safe
}
getName({ name: "Alice", age: 30 }); // works
getName({ id: 1 }); // Error: missing namekeyof constraint
function getProperty(obj: T, key: K): T[K] {
return obj[key];
}
const user = { name: "Alice", age: 30 };
getProperty(user, "name"); // string
getProperty(user, "age"); // number
getProperty(user, "email"); // Error: not a key of userThe keyof T produces a union of all keys of T as string literals. T[K] is an indexed access type โ the type of the value at key K. Together they make getProperty fully type-safe.
