What Is "keyof typeof" Used For in TypeScript?

When used together, "keyof typeof" can be used to get the property names of an object in TypeScript, where:

  • "typeof" operator works on a JavaScript value (such as a variable, constant, parameter, function, class declaration, or enum) to infer the type of the value, and;
  • "keyof" operator works on the resulting object type and provides a union of all string literals that make up its property names.

Please keep in mind the distinction between values and types when using TypeScript.

In the case where the type of an object is not directly known, you can use "typeof" to get the type of the object and then use "keyof" on the resulting type.

For example, given the following object:

const person = {
  name: 'John Doe',
  age: 29,
  status: 'active',
};

You can get the type of the "person" object using the "typeof" operator, and then use the "keyof" operator on the result to get all its property names:

// ...
type Person = typeof person; // { name: string; age: number; status: string; }
type PersonProps = keyof Person; // "name" | "age" | "status"

Alternatively, you can use "keyof typeof" to get the type of the object and its property names in one step like so:

// ...
type PersonProps = keyof typeof person; // "name" | "age" | "status"

In either case, the resulting type from using "keyof typeof" together will be a union of the string literals that represent the property names of the object, which in this case results in the union type, "name" | "age" | "status".

Using the keyof operator alone won't work in this instance, because it cannot be used directly on a value. If you do that, you will get a compile error, such as the following:

const person = {
  name: 'John Doe',
  age: 29,
  status: 'active',
};

// Error: 'person' refers to a value, but is being used as a type here.
type PersonProps = keyof person;

However, if the type of the object is already known, then you can use "keyof" directly on the type, for example, like so:

type Person = {
  name: string;
  age: number;
  status: string;
}

type PersonProps = keyof Person; // "name" | "age" | "status"

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.