[英]typescript type for all possible values of enum
So I know that keyof typeof <enum>
returns a type of all possible keys of enum, such that given 所以我知道
keyof typeof <enum>
返回一个所有可能的enum键的类型,例如
enum Season{
WINTER = 'winter',
SPRING = 'spring',
SUMMER = 'summer',
AUTUMN = 'autumn',
}
let x: keyof typeof Season;
is equivalent to 相当于
let x: 'WINTER' | 'SPRING' | 'SUMMER' | 'AUTUMN';
my question is how do I get a type that will be equivalent to one of the possible values of the enum, for example: 我的问题是如何获取与枚举的可能值之一等效的类型,例如:
let x: 'winter' | 'spring' | 'summer' | 'autumn';
Typescript doesn't allow this but as a workaround, we can make it with an object whose property values are string literals: 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
Hope this helps!!! 希望这可以帮助!!! Cheers!
干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.