【发布时间】: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
问题 - 如何让 1 与 Cat 关联
【问题讨论】:
-
我还是不明白,即使将
d的类型更改为stringCat的类型为numbertypescriptlang.org/play/…时ts也不会报警 -
将
const name: string = "Cat";更改为const name = "Cat";
标签: javascript typescript enums