TypeScript — Understanding “keyof typeof”

TypeScript has the keyof and typeof keywords allowing you to retrieve related keys and types of a value or type. We used the combination keyof typeof in tutorials here on Future Studio showing you how to get all enum keys and how to use a string as enum key.

This tutorial takes a closer look at how these keywords work.

TypeScript Series Overview

The keyof typeof Keywords in TypeScript

Let’s recap the sample code from the tutorial on how to get all enum keys in TypeScript. We have an enum for the Future Studio books mapping a slug to their titles. You can retrieve a union type of all enum keys using keyof typeof:

export enum FutureStudioBooks {  
  retrofit = 'Retrofit Book',
  picasso = 'Picasso Book',
  glide = 'Glide Book',
  gson = 'Gson Book',
  'gson-workbook' = 'Gson Workbook',
}

type FutureStudioBooksKey = keyof typeof FutureStudioBooks  
// type FutureStudioBooksKey = "retrofit" | "picasso" | "glide" | "gson" | "gson-workbook" 

Enums in TypeScript are similar to objects with strictly typed keys and values. Let’s look at an object concerning the keyof and typeof keywords.

We’re keeping the book example and creating a basic Retrofit book object. You can use typeof to create a type for the shape of an input object:

const book = {  
  slug: 'retrofit',
  title: 'Retrofit Book',
  price: 28
}

type Book = typeof book  
// type Book = {
//   slug: string;
//   title: string;
//   price: number;
// }

Now you have the type of a book object. You can now use keyof on that book object type to create a union type of all keys:

type BookProps = keyof Book;  
// type BookProps = "slug" | "title" | "price"

The combination keyof typeof on an object creates a union of literal types of all fields in the object:

const book = {  
  slug: 'retrofit',
  title: 'Retrofit Book',
  price: 28
}

type BookProps = keyof typeof book;  
// type BookProps = "slug" | "title" | "price"

As you can see, keyof typeof works the same way on enums and objects in TypeScript.

Enjoy!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.