Lesson 10 of 56 · Typescript
Generic Constraints
Duration: 25 minutes
Constraining Generics with extends
interface Lengthwise { length: number; }
function logLength<T extends Lengthwise>(arg: T): void {
console.log(arg.length);
}
logLength([1, 2, 3]); // OK – arrays have length
logLength("hello"); // OK – string has length
// logLength(123); // ❌ number doesn't have length
Using keyof to constrain property names
function getProp<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}
const person = { name: "Bob", age: 30 };
const name = getProp(person, "name"); // inferred as string
Conditional Types with Generics
type NonNullable<T> = T extends null | undefined ? never : T;
type NN = NonNullable<string | undefined>; // string