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';
f.khantsis
  • 3,256
  • 5
  • 50
  • 67
  • 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;`) – jcalz Sep 18 '19 at 19:01
  • 1
    very good explanation provided in this link https://stackoverflow.com/questions/52393730/typescript-string-literal-union-type-from-enum – Siddharth Pal Sep 18 '19 at 19:12
  • @jcalz I can't do `let x: Season = 'winter';` – f.khantsis Sep 18 '19 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 = 'winter'`, what would you do with it? I want to see more of a use case here – jcalz Sep 18 '19 at 19:23

2 Answers2

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!

Siddharth Pal
  • 1,408
  • 11
  • 23
2

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'