enum Direction {
Up = 1,
Down,
Left,
Right
}
if (typeof Direction === 'enum') {
// doesn't work
}
Any way to check if the above is in fact an enum?
Enums are compiled into simple objects that have two way mapping:
name => value
value => name
So the enum in your example compiles to:
var Direction;
(function (Direction) {
Direction[Direction["Up"] = 1] = "Up";
Direction[Direction["Down"] = 2] = "Down";
Direction[Direction["Left"] = 3] = "Left";
Direction[Direction["Right"] = 4] = "Right";
})(Direction || (Direction = {}));
So the typeof of Direction is a plain "object".
There's no way of knowing in runtime that the object is an enum, not without adding more fields to said object.
Sometimes you don't need to try to workaround a problem with a specific approach you have, you can maybe just change the approach.
In this case, you can use your own object:
interface Direction {
Up: 1,
Down: 2,
Left: 3,
Right: 4
}
const Direction = {
Up: 1,
Down: 2,
Left: 3,
Right: 4
} as Direction;
Or:
type Direction = { [name: string]: number };
const Direction = { ... } as Direction;
Then turning this object into an array should be simple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With