如何在打字稿枚举上反向打字? [英] How to reverse typing on a typescript enum?

查看:54
本文介绍了如何在打字稿枚举上反向打字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出打字稿中的枚举

enum CoffeeSizes {
  Large = 'L',
  Medium = 'M',
  ExtraLarge = 'XL',
}

CoffeeSizes.Large === 'L' // true

如何进行反向查找,在哪里可以说

How do I do the reverse lookup, where I can say

CoffeeSizes.L === 'Large'

如何创建带有反枚举的类型?

How can I create a type with the inverse enum?

推荐答案

反向映射仅适用于数字非const枚举.
如下面的示例

Reverse mappings are only possible for numeric non const enums.
As in the example below

enum CoffeeSizes {
  Large,
  Medium,
  ExtraLarge
}

const nameOffLargeCoffeeSize = CoffeeSizes[CoffeeSizes.Large];
CoffeeSizes[nameOffLargeCoffeeSize] === CoffeeSizes.Large;

您可以在 TypeScript文档中获取更多详细信息

You can get more details in TypeScript docs

这篇关于如何在打字稿枚举上反向打字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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