enum Direction {
Up = 1,
Down,
Left,
Right
}
if (typeof Direction === 'enum') {
// doesn't work
}
有没有办法检查上面的代码是否确实是一个枚举
?
enum Direction {
Up = 1,
Down,
Left,
Right
}
if (typeof Direction === 'enum') {
// doesn't work
}
有没有办法检查上面的代码是否确实是一个枚举
?
枚举被编译成简单对象,具有双向映射:
name => value
value => name
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 = {}));
Direction
的typeof
是一个普通的"object"
。在运行时无法知道该对象是否为枚举类型,除非向该对象添加更多字段。
有时候你不需要尝试使用特定的方法来解决问题,你可以改变方法。
在这种情况下,你可以使用自己的对象:
interface Direction {
Up: 1,
Down: 2,
Left: 3,
Right: 4
}
const Direction = {
Up: 1,
Down: 2,
Left: 3,
Right: 4
} as Direction;
或者:
type Direction = { [name: string]: number };
const Direction = { ... } as Direction;
就记录而言,以下是一种确定对象是否为枚举的方法:
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;
}