简体   繁体   中英

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

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?

The answer to the question as asked is to query the keys (viathe 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM