打字稿中常量类型的最佳做法是什么?

时间:2020-06-21 09:10:06

标签: typescript typescript-typings

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 as const //correct
export let a3: PositionType = 3 //typescript error

我不想编写这样的代码type PositionType = 1 | 2,添加枚举时,我不想更改类型

1 个答案:

答案 0 :(得分:0)

TypeScript不会跟踪Enum值的特定文字类型。当您看到以下内容也没有类型错误时,这将变得更加明显:

let x: typeof ENUM_POSITION_TYPE["LEFT"] = 3;

我建议采用以下方法

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

type PositionType = typeof ENUM_POSITION_TYPE[keyof typeof ENUM_POSITION_TYPE];
相关问题