enum ENUM_POSITION_TYPE {
LEFT = 1,
RIGHT = 2
}
// type PositionType = ENUM_TYPE.LEFT | ENUM_TYPE.RIGHT
type PositionType = ???
//期望
export let a1: PositionType = ENUM_POSITION_TYPE.RIGHT //correct
export let a2: PositionType = 1 //correct
export let a3: PositionType = 3 //typescript error
###
你是想在编译时约束枚举类型的值?
这是不行的,TS 中的枚举类型,其实就是个 number / string 的别名类。
TS 官方文档中是这么描述的:
Enum types are assignable to the Number primitive type, and vice versa, but different enum types are not assignable to each other.
要么你可以在运行时做判断:
enum ENUM_POSITION_TYPE {
LEFT = 1,
RIGHT = 2
}
function foo(e: ENUM_POSITION_TYPE) {
if (!(e in ENUM_POSITION_TYPE)) {
throw new TypeError();
}
}
要么你就别声明 enum,直接用 number 字面量:
type ENUM_POSITION_LEFT = 1;
type ENUM_POSITION_RIGHT = 2;
type PositionType = ENUM_POSITION_LEFT | ENUM_POSITION_RIGHT;