typescript 常量最佳实践

新手上路,请多包涵
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
阅读 1.9k
1 个回答

你是想在编译时约束枚举类型的值?

这是不行的,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;
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进