【问题标题】:typescript type for all possible values of enum枚举所有可能值的打字稿类型
【发布时间】:2019-09-18 18:49:55
【问题描述】:

所以我知道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';

【问题讨论】:

  • Season 类型等于枚举对象值的并集,尽管Season'winter' | 'spring' | 'summer' | 'autumn'子类型Season 不适合你吗? (例如,declare let s: Season; let x: 'winter' | 'spring' | 'summer' | 'autumn' = s;
  • 这个链接提供了很好的解释stackoverflow.com/questions/52393730/…
  • @jcalz 我做不到let x: Season = 'winter';
  • 你能解释一下为什么你需要访问枚举的裸字符串文字版本吗?例如,为什么不直接使用本质上相同的let x: Season = Season.WINTER?即使你能做到let x: Magic<Season> = 'winter',你会用它做什么?我想在这里看到更多的用例

标签: typescript


【解决方案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

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

【讨论】:

  • 谢谢,但枚举定义来自外部库
猜你喜欢
  • 2019-07-09
  • 2017-03-09
  • 2020-09-16
  • 2020-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-30
相关资源
最近更新 更多