【问题标题】:Access number enum passing string访问号码枚举传递字符串
【发布时间】:2018-03-03 01:41:42
【问题描述】:

我正在尝试基于动物name 访问id

enum Animals {
  Cat = 1,
  Dog,  // 2
}

const name: string = "Cat";

const id: number = Animals[name] // Element implicitly has an 'any' type because index expression is not of type 'number'.

转自https://basarat.gitbooks.io/typescript/docs/enums.html#enums-and-strings

enum Tristate {
  False,
  True,
  Unknown
}

console.log(Tristate["False"]); // 0

问题 - 如何让 1Cat 关联

【问题讨论】:

标签: javascript typescript enums


【解决方案1】:

当您使用变量(例如,name)来处理枚举的值时,如果您将类型定义为string,它认为它可以包含任何值,甚至不存在于枚举。所以输出变成了any

为避免此问题,您可以直接调用枚举 (Animals['Cat']),也可以将变量的值限制为枚举值,如下所示:

const name: 'Cat' | 'Dog' = 'Cat';
const id: number = Animals[name]; // 1

【讨论】:

  • 你是对的,但最直接的解决方法是删除类型注释并让编译器推断类型:const name = "Cat"; 将推断名称为"Cat" 类型。
  • 正确,但如果变量的输入在运行时来自其他来源,我们可以通过这种方式确保类型。
  • 其实在那种情况下,类型是错误的。类型注释对运行时没有任何影响。
  • 我在考虑一个基于某些输入的函数返回 'Cat' | 'Dog' 的情况。在这种情况下,此类型注释强制使用 Animals 枚举类型。我同意在运行时可能会传递任何值,但是具有此定义类型的中间函数可能有助于消除该问题。想法?
  • 我建议定义一个检查值的中间类型保护函数。 function inEnum(k: string): k is keyof Animals {return Object.keys(Animals).includes(k);}。这将做正确的事情并将类型推出,因此它们是验证值的结果
猜你喜欢
  • 2018-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多