是否可以在 typescript 中获取枚举的第一项?
例如,此枚举中的Option.All
:
enum Option {
All = "all",
Mine = "mine",
}
尝试过,但无法编译:
const first: Option = Option[0]; // first should be All. This won't compile - Property '0' does not exist on type 'typeof Option'.
最佳答案
Option 本质上是一个对象。
编译成JS时是这样定义的:
var Option;
(function (Option) {
Option["All"] = "all";
Option["Mine"] = "mine";
})(Option || (Option = {}));
您可以使用 Object.keys() 或 Object.values() 将对象转换为数组。
因此,为了使 first = 'All',您可以使用:
enum Option {
All = "all",
Mine = "mine",
}
const first = Object.keys(Option)[0];
console.log(first)
如果您想了解 TS 和 JS 之间的外观,可以使用 TS Playground .我已将此链接与我在此处显示的代码一起加载。
如果您希望 firstValue 的类型为 Option,请使用 Object.values(Option)[0]
。
Typescript playground 的名称 Option
似乎有问题,因此如果您将其更改为 Options
,它会正确显示 first 是 Options< 类型
:Playground
enum Options {
All = "all",
Mine = "mine",
}
const first = Object.values(Options)[0];
console.log(first) // 'all' of type Options
我的本地环境没有表现出同样的怪异。
关于typescript - 从枚举中获取第一个枚举项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64377506/