Understanding the keyof Type Operator in TypeScript

Hemanta Sundaray

Published December 28, 2023


The keyof operator in TypeScript takes a type and returns a union type of its keys.

Let's say we have the following type:

type User = {
  id: number;
  name: string;
  email: string;
};

Applying keyof to this User type:

type UserKeys = keyof User;

Here, UserKeys is a new type, equivalent to:

type UserKeys = "id" | "name" | "email";

Each member of the union id, name, and email) is a string literal type corresponding to one of the keys in the User interface.

Using keyof with Variables

To apply keyof on a variable, we first need to determine its type. This is where the typeof operator becomes useful.

Suppose we have an object:

const car = {
  make: "Toyota",
  model: "Corolla",
  year: 2021,
};

We can use typeof operator to dynamically obtain the type information from the car variable itself:

type carType = typeof car;

When we apply typeof to car, TypeScript evaluates it to the type of the variable car, which is an object type with the following structure:

{
  make: string;
  model: string;
  year: number;
}

Now that we have the type of the car object, we can use the keyof operator to create a union of its keys:

type CarKeys = keyof typeof car;
 
// CarKeys is now "make" | "model" | "year"