1

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';
4
  • The type Season is equal to the union of the enum object's values, although Season is a subtype of 'winter' | 'spring' | 'summer' | 'autumn'. Does Season not work for you? (e.g., declare let s: Season; let x: 'winter' | 'spring' | 'summer' | 'autumn' = s;) Commented Sep 18, 2019 at 19:01
  • 1
    very good explanation provided in this link stackoverflow.com/questions/52393730/… Commented Sep 18, 2019 at 19:12
  • @jcalz I can't do let x: Season = 'winter'; Commented Sep 18, 2019 at 19:13
  • Can you explain why you need access to bare string literal versions of the enum? For example, why not just use let x: Season = Season.WINTER which is essentially the same thing? Even if you could do let x: Magic<Season> = 'winter', what would you do with it? I want to see more of a use case here Commented Sep 18, 2019 at 19:23

2 Answers 2

3

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'
Sign up to request clarification or add additional context in comments.

Comments

2

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!

1 Comment

thanks, but the enum definition comes from an external library

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.