typescript 常量的最佳实践

enum ENUM_POSITION_TYPE {
  LEFT = 1,
  RIGHT = 2
}

// type PositionType = 1 | 2
type PositionType = ???

export let a1: PositionType = ENUM_POSITION_TYPE.RIGHT //correct
export let a2: PositionType = 1 //correct
export let a3: PositionType = 3 //typescript error

我不想让 type PositionType = 1 | 2,因为这样写,我如果在ENUM_POSITION_TYPE加一个枚举,我还要在改写一下PositionType

阅读 1.8k
1 个回答

枚举存在的意义不就是代替直接数字量吗?为什么还需要映射一个有限数字集类型?

export enum ENUM_POSITION_TYPE {
  LEFT = 1,
  RIGHT = 2
}

export let a1: ENUM_POSITION_TYPE = ENUM_POSITION_TYPE.RIGHT //correct
export let a2: ENUM_POSITION_TYPE = 1 //correct

直接导出 ENUM_POSITION_TYPE 不好吗?


我觉得我明白了你的疑问,大概是跟 这个 ISSUE 提到的一样。它下面有一个解决办法,或者你可以试试:


export const ENUM_POSITION_TYPE = {
    LEFT: 1,
    RIGHT: 2
} as const;

type PositionType = typeof ENUM_POSITION_TYPE[keyof typeof ENUM_POSITION_TYPE];

export let a1: PositionType = ENUM_POSITION_TYPE.RIGHT; //correct
export let a2: PositionType = 1; //correct
export let a3: PositionType = 3; //typescript error
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进