枚举的所有可能值的打字稿类型

时间:2019-09-18 18:49:55

标签: typescript

所以我知道keyof typeof <enum>返回一种所有可能的枚举键的类型,例如给定的

enum Season{
 WINTER = 'winter',
 SPRING = 'spring',
 SUMMER = 'summer',
 AUTUMN = 'autumn',
}
let x: keyof typeof Season;

等效于

let x: 'WINTER' | 'SPRING' | 'SUMMER' | 'AUTUMN';

我的问题是如何获取与枚举的可能值之一等效的类型,例如:

let x: 'winter' | 'spring' | 'summer' | 'autumn';

1 个答案:

答案 0 :(得分:1)

Typescript不允许这样做,但是作为一种解决方法,我们可以使用其属性值为字符串文字的对象来实现它:

  const createLiteral = <V extends keyof any>(v: V) => v;
  const Season = {
   WINTER: createLiteral("winter"),
   SPRING: createLiteral("spring"),
   SUMMER: createLiteral("summer")
  }
  type Season = (typeof Season)[keyof typeof Season]
  const w: Season = "winter"; // works
  const x: Season = "sghjsghj"; // error

希望这会有所帮助!!!干杯!