How do I access Typescript Enum by ordinal

时间:2016-09-10 15:24:21

标签: typescript

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'.

5 个答案:

答案 0 :(得分:13)

当您声明某些内容属于NubDirection类型时,它实际上是一个数字:

var a = NubDirection.INWARD;
console.log(a === 1); // true

当您使用序数访问枚举时,您会返回一个字符串而不是数字,因此您无法将其分配给声明为NubDirection的内容。

你可以这样做:

nub.direction = NubDirection[NubDirection[index]];

这样做的原因是javascript中没有enum这样的东西,而且typescript模仿枚举的方式是在将它编译为js时这样做:

var NubDirection;
(function (NubDirection) {
    NubDirection[NubDirection["OUTWARD"] = 0] = "OUTWARD";
    NubDirection[NubDirection["INWARD"] = 1] = "INWARD";
})(NubDirection || (NubDirection = {}));

所以你最终得到了这个对象:

NubDirection[0] = "OUTWARD";
NubDirection[1] = "INWARD";
NubDirection["OUTWARD"] = 0;
NubDirection["INWARD"] = 1;

答案 1 :(得分:8)

如果您有这样的字符串枚举:

export enum LookingForEnum {
    Romantic = 'Romantic relationship',
    Casual = 'Casual relationship',
    Friends = 'Friends',
    Fun = 'Fun things to do!'
}

然后

 const index: number = Object.keys(LookingForEnum).indexOf('Casual'); // 1

答案 2 :(得分:3)

您可以使用:

export enum SpaceCargoShipNames {
  Gnat = 'Gnat',
  Orilla = 'Orilla',
  Ambassador = 'Ambassador',
  CarnarvonBay = 'Carnarvon Bay'
}

然后:

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());                

答案 3 :(得分:1)

以上所有答案都对我没有帮助。您可以做的事情是这样的:

// Do whatever math operation with an index you wish...
...

// Get the the enum string value:
const nextStringedEnum: string = Object.values(NubDirection)[nextIndex];

// Get the typed enum from the string value:
const nextIndex: NubDirection = Object.values(NubDirection).indexOf(nextStringedEnum);

答案 4 :(得分:0)

使用此:

Report.Rmd