Reputation: 3540
So I know that keyof typeof <enum>
returns a type of all possible keys of enum, such that given
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';
Upvotes: 1
Views: 810
Reputation: 31
I had the same question. Solved it with this:
enum Season{
WINTER = 'winter',
SPRING = 'spring',
SUMMER = 'summer',
AUTUMN = 'autumn',
}
type SeasonEnumValues = `${Season}`;
SeasonEnumValues is equivalent to the following:
type SeasonEnumValues = 'winter' | 'spring' | 'summer' | 'autumn'
Upvotes: 3
Reputation: 1458
Typescript doesn't allow this but as a workaround, we can make it with an object whose property values are string literals:
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!
Upvotes: 2