如何按顺序访问 Typescript Enum
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39427542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I access Typescript Enum by ordinal
提问by Hymanie
I have the following...
我有以下...
enum NubDirection {
OUTWARD,
INWARD
}
...
direction : NubDirection;
...
let index = Math.floor(Math.random() * 2) + 1;
nub.direction = NubDirection[index];
But this throws
但这会抛出
error TS2322: Type 'string' is not assignable to type 'NubDirection'.
错误 TS2322:“字符串”类型不可分配给“NubDirection”类型。
回答by Nitzan Tomer
When you declare that something is of type NubDirection
then it's actually a number:
当你声明某物是某种类型时,NubDirection
它实际上是一个数字:
var a = NubDirection.INWARD;
console.log(a === 1); // true
When you access the enum using the ordinal you get back a string and not a number and because of that you can not assign it to something that was declared as NubDirection
.
当您使用序数访问枚举时,您会返回一个字符串而不是数字,因此您无法将其分配给声明为NubDirection
.
You can do:
你可以做:
nub.direction = NubDirection[NubDirection[index]];
The reason for this is that there's no such thing as enum in javascript, and the way typescript imitates enums is by doing this when compiling it to js:
这样做的原因是javascript中没有enum这样的东西,而typescript模仿enum的方式是在编译成js时这样做:
var NubDirection;
(function (NubDirection) {
NubDirection[NubDirection["OUTWARD"] = 0] = "OUTWARD";
NubDirection[NubDirection["INWARD"] = 1] = "INWARD";
})(NubDirection || (NubDirection = {}));
So you end up with this object:
所以你最终得到这个对象:
NubDirection[0] = "OUTWARD";
NubDirection[1] = "INWARD";
NubDirection["OUTWARD"] = 0;
NubDirection["INWARD"] = 1;
回答by Sampath
If you have string enum like so:
如果你有这样的字符串枚举:
export enum LookingForEnum {
Romantic = 'Romantic relationship',
Casual = 'Casual relationship',
Friends = 'Friends',
Fun = 'Fun things to do!'
}
Then
然后
const index: number = Object.keys(LookingForEnum).indexOf('Casual'); // 1
回答by KubaMiszcz
you may use:
你可以使用:
export enum SpaceCargoShipNames {
Gnat = 'Gnat',
Orilla = 'Orilla',
Ambassador = 'Ambassador',
CarnarvonBay = 'Carnarvon Bay'
}
and then:
接着:
let max = Object.keys(SpaceCargoShipNames).length; //items count
let n = Math.round(Math.random() * max); //random index
let v = Object.values(SpaceCargoShipNames)[n]; //item
console.log(max, n, v, v.valueOf());