Typescript 枚举的所有可能值的类型脚本类型

Typescript 枚举的所有可能值的类型脚本类型,typescript,Typescript,所以我知道keyof-typeof返回一种类型的所有可能的enum键,例如 枚举季节{ 冬季=‘冬季’, SPRING='SPRING', SUMMER=‘SUMMER’, 秋天=‘秋天’, } 设x:typeof季节; 相当于 让x:‘冬天’|‘春天’|‘夏天’|‘秋天’; 我的问题是如何获得与枚举的一个可能值等效的类型,例如: let x: 'winter' | 'spring' | 'summer' | 'autumn'; Typescript不允许这样做,但作为一种解决方法,我们

所以我知道
keyof-typeof
返回一种类型的所有可能的enum键,例如

枚举季节{
冬季=‘冬季’,
SPRING='SPRING',
SUMMER=‘SUMMER’,
秋天=‘秋天’,
}
设x:typeof季节;
相当于

让x:‘冬天’|‘春天’|‘夏天’|‘秋天’;
我的问题是如何获得与枚举的一个可能值等效的类型,例如:

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

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
constcreateliteral=(v:v)=>v;
恒定季节={
冬季:createLiteral(“冬季”),
SPRING:createLiteral(“SPRING”),
夏季:createLiteral(“夏季”)
}
季节类型=(季节类型)[季节类型键]
const w:季节=“冬季”//作品
const x:Season=“sghjsghj”//错误

希望这有帮助!!!干杯

类型
seasure
等于枚举对象值的并集,尽管
seasure
'winter'|'spring'|'summer'|'秋'
的子类型。
Season
不适合你吗?(例如,
声明let s:Season;let x:'winter'|'spring'|'summer'|'秋天'=s;
)在这个链接中提供了非常好的解释@jcalz我做不到
let x:Season='winter'您能解释一下为什么需要访问枚举的裸字符串文本版本吗?例如,为什么不使用本质上相同的东西?即使你可以做
让x:Magic='winter'
,你会用它做什么?我想在这里看到更多的用例,谢谢,但是枚举定义来自外部库