有没有办法检查对象是否是 TypeScript 中的枚举类型?

jcr*_*oll 5 typescript

enum Direction {
    Up = 1,
    Down,
    Left,
    Right
}

if (typeof Direction === 'enum') {
    // doesn't work
}
Run Code Online (Sandbox Code Playgroud)

有什么方法可以检查上面的内容是否实际上是一个enum

Nit*_*mer 6

枚举被编译成具有两种映射方式的简单对象:

name => value
value => name
Run Code Online (Sandbox Code Playgroud)

因此,示例中的枚举编译为:

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 = {}));
Run Code Online (Sandbox Code Playgroud)

所以typeofofDirection是一个普通的"object".
如果不向所述对象添加更多字段,则无法在运行时知道该对象是枚举。


编辑

有时,您不需要尝试使用现有的特定方法来解决问题,您也许只需更改方法即可。
在这种情况下,您可以使用自己的对象:

interface Direction {
    Up: 1,
    Down: 2,
    Left: 3,
    Right: 4
}
const Direction = {
    Up: 1,
    Down: 2,
    Left: 3,
    Right: 4
} as Direction;
Run Code Online (Sandbox Code Playgroud)

或者:

type Direction = { [name: string]: number };
const Direction = { ... } as Direction;
Run Code Online (Sandbox Code Playgroud)

然后把这个对象变成数组应该很简单。