How do I access Typescript Enum by ordinal
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;
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