The keyof is a keyword in TypeScript that creates a union type of all the properties in an object. The type that is created is called a lookup type. This allows us to create types dynamically, based on the properties of an existing type. It's a useful feature that we can use to create generic but strongly typed code against varying data.
Let's go through an example:
- We have the following IPerson interface:
interface IPerson {
id: number;
name: string;
}
- Let's create a lookup type on this interface using keyof:
type PersonProps = keyof IPerson;
If we hover over the PersonProps type, we see that a union type containing "id" and "name" has been created:
- Let's add a new property to IPerson:
interface IPerson {
id: number;
name: string;
age: number
}
If we hover over the PersonProps type again, we see that...