6

TypeScript 中根据枚举类型的值获取对应数据

 2 years ago
source link: https://www.mivm.cn/typescript-enum-text
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

TypeScript 中根据枚举类型的值获取对应数据

2020-08-26 607点热度 2人点赞 0条评论

index.png

TypeScript 中有很多有用的特性,枚举(Enum)就是其中之一,可以让我们事先定义一组常量,以便用于类型声明。

但是小山最近至写代码的时候遇到一种需求,就是通过枚举类型的值来获取对应数据。

比如我有一个这样的数据接口和枚举:

interface Purchase {
schedule: Schedule;
enum Schedule {
not = 1,
reported,
stored,
interface Purchase {
  schedule: Schedule;
}

enum Schedule {
  not = 1,
  reported,
  stored,
}

现在获取到的值只是枚举的值(1, 2, 3),这些值无法直接呈现给用户,需要使用这些值来获取/转换对应的数据,最常见就是转换成文本。

如果是简单文本,其实还比较简单,可以把枚举的键写成需要的文本,由于 TS 里的枚举是双向的,所以你可以用值获取到键。比如Schedule[Schedule.not]获取到的就是"not"

但是复杂的数据,就不能用这种方法了,而且如果要获取的文本是中文,虽然键可以用中文声明,不过我们写代码一般不提倡使用中文来作为变量的名称。

所以当我们有上述需求的时候,可以使用下面这种方法声明一个对象,而且这种声明是安全的。

const ScheduleText: { [key in Schedule]: string } = {
[Schedule.not]: '暂无进度',
[Schedule.reported]: '已报',
[Schedule.stored]: '已入库',
// 以下写法不会报错
ScheduleText[ScheduleText.not];
// 当然也可以这样写
ScheduleText['1'];
const ScheduleText: { [key in Schedule]: string } = {
  [Schedule.not]: '暂无进度',
  [Schedule.reported]: '已报',
  [Schedule.stored]: '已入库',
};

// 以下写法不会报错

ScheduleText[ScheduleText.not];


// 当然也可以这样写

ScheduleText['1'];

这个对象的声明是用 Schedule 的值作为键并且值为字符串,这样的类型检查比较方便,当你的枚举有新添加的值,而对象没有被更新,则会报错,并且它是一个对象,值可以是任何类型,也可以是动态的值。

不过这种方法有一个弊端,就是所有对象的类型声明都需要这样写{ [key in Schedule]: string },你没办法用泛型声明一个 Type,因为泛型目前没有支持枚举。


如果你有更好的方法,欢迎在下面评论,也可以加入 QQ 群小山交流更多其他的知识。

微信公众号二维码

微信扫描二维码关注我们

如果觉得文章有帮助到你,可以点击下方的打赏按钮赞助下服务器费用。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK