使用枚举作为字典键 [英] Using an enum as a dictionary key

查看:516
本文介绍了使用枚举作为字典键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为给定的枚举创建有保证的查找.与之类似,对于枚举的每个键,在查找中应该只存在一个值.我想通过类型系统保证这一点,以便在枚举扩展时不会忘记更新查找.我试过了:

I'm trying to create a guaranteed lookup for a given enum. As in, there should be exactly one value in the lookup for every key of the enum. I want to guarantee this through the type system so that I won't forget to update the lookup if the enum expands. I tried this:

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

enum Direction {
    Up,
    Down,
}

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

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

But I'm getting this weird error:

键入'{[Direction.Up]:数字; [Direction.Down]:数字; }"不能分配给方向"类型.

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

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

Which seems weird to me because it's saying that the type of lookup should be Direction instead of EnumDictionary<Direction, number>. I can confirm this by changing the lookup declaration to:

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

没有错误.

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

How can I create a lookup type for an enum that guarantees every value of the enum will lead to another value of a different type?

TypeScript版本:3.2.1

TypeScript version: 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
};

我感到惊讶,直到我意识到可以将枚举视为专用联合类型.

I found it surprising until I realised that enums can be thought of as a 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 类型:

The EnumDictionary defined this way is basically the built in Record type:

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

这篇关于使用枚举作为字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆