Generic and keyof

This lesson explains how to combine keyof with generic.

We'll cover the following...

You can use extends to extend a generic type to another type if you want the generic type to be a subset of the other type.

In the following code, we see that line 13 expects that the generic K extends T, which means that the second parameter needs to extend the former.

Press + to interact
interface TypeA {
prop1: string;
prop2: number;
}
interface TypeB {
prop1: string;
prop3: boolean;
}
interface TypeC extends TypeA {
prop4: number;
}
function printProps<T, K extends T>(p1: T, p2: K): void { // K must have all field from T at minimum
console.log(p1);
console.log(p2);
}
let a: TypeA = { prop1: "p1", prop2: 2 };
let b: TypeB = { prop1: "p1", prop3: true };
let c: TypeC = { prop1: "p1", prop2: 2, prop4: 4 };
// printProps(a, b); // Does not transpile because B does not extends A
printProps(a, c);

The ...