Home > Mobile >  TypeScript: How to get the keys of an enum as type?
TypeScript: How to get the keys of an enum as type?

Time:11-21

I want to get the keys of an enum as a type, to make my application type safe in other parts.

Take a look at this code snippet:

enum Layers {
    Front = 1,
    Middle = 2,
    Back = 3,
}

type LayerKeys = key in Layers; // <--- THIS PSEUDOCODE IS NOT WORKING

type LayerConfig = Map<LayerKeys, {}>;

How can I correctly get the enum keys here?

CodePudding user response:

As already suggested you could use directly the enum Layers as part of the map definition, but if you want to try to use the keys instead you can use this lib ts-enum-util; It provides a series of utilities around enums

enum Layers {
    Front = 1,
    Middle = 2,
    Back = 3,
}

const keys = $enum(Layers).getKeys();


type LayerKeys = typeof keys[number]

type LayerConfig = Map<LayerKeys, {}>;

with $enum(Layers).getKeys() you retrieve the key list of enum as array, and then you can use this array as type specification

CodePudding user response:

The answer to the question as asked is to query the keys (via the keyof type operator of the object named Layers. That object has a type which can be acquired via the typeof type operator:

type LayerKeys = keyof typeof Layers
// type LayerKeys = "Front" | "Middle" | "Back"

Playground link to code

  • Related