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?
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.
For the record, here's a method that will determine if an object is an enum:
isEnum(instance: Object): boolean {
let keys = Object.keys(instance);
let values = [];
for (let key of keys) {
let value = instance[key];
if (typeof value === 'number') {
value = value.toString();
}
values.push(value);
}
for (let key of keys) {
if (values.indexOf(key) < 0) {
return false;
}
}
return true;
}