Learn TypeScript

Using `keyof`

Using `keyof`

In this lesson, we will learn how to use the keyof operator to extract the keys from an object in a type annotation.

Understanding the keyof operator

The syntax for using a keyof operator in a type annotation is as follows:

let keys: keyof ExistingType;

The keyof operator is sometimes referred to as the index query operator because it queries the type specified after it. When TypeScript sees the keyof operator in a type annotation, it queries the type after it and extracts all its keys. It then constructs a union string literal type from the keys.

An example

We are going to explore the keyof operator in the code editor below:

TypeScriptOpen exercise in CodeSandbox

The editor contains a ContactDetails type.

  • Create a variable called keys:
let keys;
  • Add a type annotation to keys that uses the keyof operator on the ContactDetails type.
🤔

What is the type of the keys variable?

  • Add an additional property to the ConactDetails type:
type ContactDetails = {
...
mobile: string;
};
🤔

What is the type of the keys variable now?

Neat!

Summary

The keyof type annotation can be used to extract the keys from an object. This is a key ingredient for creating mapped types which we will explore in the next lesson.

© 2020 Carl Rippon
Privacy Policy
This site uses cookies. Click here to find out more