Search⌘ K

Generic and keyof

Explore how to use generics with extends and keyof in TypeScript to create flexible and strongly typed functions. Understand how constraining keys with keyof ensures only valid property names are used, enhancing type safety and preventing runtime errors.

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.

TypeScript 3.3.4
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 ...