typescript - 使用枚举作为字典键

标签 typescript dictionary enums

我正在尝试为给定的枚举创建有保证的查找。就像在查找枚举的每个键时,应该恰好有一个值。我想通过类型系统来保证这一点,这样我就不会忘记在枚举扩展时更新查找。我试过这个:

type EnumDictionary<T, U> = {
    [K in keyof T]: U;
};

enum Direction {
    Up,
    Down,
}

const lookup: EnumDictionary<Direction, number> = {
    [Direction.Up]: 1,
    [Direction.Down]: -1,
};

但是我遇到了这个奇怪的错误:

Type '{ [Direction.Up]: number; [Direction.Down]: number; }' is not assignable to type 'Direction'.

这对我来说似乎很奇怪,因为它说 lookup 的类型应该是 Direction而不是 EnumDictionary<Direction, number> .我可以通过更改 lookup 来确认这一点声明:

const lookup: EnumDictionary<Direction, number> = Direction.Up;

没有错误。

我如何为枚举创建一个查找类型,以保证枚举的每个值都会导致另一个不同类型的值?

TypeScript 版本:3.2.1

最佳答案

您可以按如下方式进行:

type EnumDictionary<T extends string | symbol | number, U> = {
    [K in T]: U;
};

enum Direction {
    Up,
    Down,
}

const a: EnumDictionary<Direction, number> = {
    [Direction.Up]: 1,
    [Direction.Down]: -1
};

直到我意识到枚举可以被认为是 specialised union type 之前,我感到很惊讶。 .

The other change is that enum types themselves effectively become a union of each enum member. While we haven’t discussed union types yet, all that you need to know is that with union enums, the type system is able to leverage the fact that it knows the exact set of values that exist in the enum itself.

以这种方式定义的 EnumDictionary 基本上是内置的 Record输入:

type Record<K extends string, T> = {
    [P in K]: T;
}

关于typescript - 使用枚举作为字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54542318/

相关文章:

typescript - 如何解决 "Failed to load config "airbnb-typescript"to extend from."on Google Cloud Build?

Python 有选择地从字典中查找并打印值

python - 根据匹配值合并 2 个字典列表,否则保持原始?

java - FreeMarker 模板中的枚举错误

javascript - 展平嵌套对象而不出现 TS 错误

javascript - JSON 到 JSON 转换 : Flattening

javascript - Typescript 在导入 Node.js 时找不到自己类的名称

python - 使用字典制作 matplotlib 图?

swift - 将 Objective-C (#define) 宏转换为 Swift

c# - 解析字符串以匹配枚举值