简体   繁体   English

TypeScript:如何获取枚举类型的键?

[英]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 :所问问题的答案是查询键(通过名为Layersobjectkeyof类型运算符。object 具有可以通过typeof类型运算符获取的类型:

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 ;正如已经建议的那样,您可以直接使用枚举层作为 map 定义的一部分,但是如果您想尝试使用键,您可以使用这个库ts-enum-util It provides a series of utilities around enums它提供了一系列围绕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$enum(Layers).getKeys()检索枚举的键列表作为数组,然后你可以使用这个数组作为类型规范

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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