Jackie Jackie - 1 year ago 148
TypeScript Question

How do I access Typescript Enum by ordinal

I have the following...

enum NubDirection {
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'.

Answer Source

When you declare that something is of type NubDirection then it's actually a number:

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.

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:

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;