Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to check if an object is a type of enum in TypeScript?

Tags:

typescript

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?

like image 866
jcroll Avatar asked Feb 02 '17 15:02

jcroll


1 Answers

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.


Edit

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.

like image 83
Nitzan Tomer Avatar answered Oct 21 '22 04:10

Nitzan Tomer