TypeScript — Get All Keys of an Enum

Enums in TypeScript are a feature that is not only a type-level extension to JavaScript. They also carry a named set of constants. TypeScript supports numeric enums and string enums. Both use string values for their identifiers.

This tutorial shows you how to retrieve all available keys of a TypeScript enum.

TypeScript Series Overview

Get All Keys of a TypeScript Enum

You can imagine TypeScript enums as JavaScript objects. And you can retrieve the keys from an object using the Object.keys() method. Do it the same way to retrieve an enum’s keys in TypeScript!

Here’s an example of getting a list of enum keys in TypeScript using Object.keys():

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

const keys = Object.keys(FutureStudioBooks)  
// ['retrofit', 'picasso', 'glide', 'gson', 'gson-workbook']

The keys property now contains the enum’s keys as an array.

Narrowing the TypeScript Enum Keys Type

A downside of using Object.keys() is that the resulting array has the string[] type:

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

const keys = Object.keys(FutureStudioBooks)  
// const keys: string[]

You’re not having the narrowed types from the enum’s keys. You may have expected that TypeScript knows which keys are part of the enum and narrows the returned list to only these options. But the method signature of Object.keys is this:

interface ObjectConstructor {  
    keys(o: object): string[];
}

You can still narrow the types of your array manually. Create a new type of the enum keys with the help of TypeScript’s keyof typeof types and the enum itself. You can then assert the result of Object.keys to a narrowed array containing only the enum keys:

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"

const keys = Object.keys(FutureStudioBooks) as FutureStudioBooksKey[]  
// const keys: ("retrofit" | "picasso" | "glide" | "gson" | "gson-workbook")[]

That’s it!

Explore the Library

Find interesting tutorials and solutions for your problems.