Lookup and mapped types

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:

  1. We have the following IPerson interface:
interface IPerson {  id: number;  name: string;}
  1. 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:

  1. Let's add a new property to IPerson:
interface IPerson { ...

Get Learn React with TypeScript 3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.