SimplGy
SimplGy

Reputation: 20437

Calculate union of strings from enum keys

Is there a way to calculate a union of string keys for a given enum?

For example, given this:

enum Fruits {
    Apple = 2,
    Orange = 3,
}

I'd like to generate a FruitKey type with this value:

type FruitKey = 'Apple'|'Orange'; // generate this

Here's what I tried. I thought Extract and index types would help, but they don't work because keyof doesn't work on enums.

type Keys = keyof Fruits; // Nope. Doesn't work, actually these are object props, not record keys.
type AllValues = Fruits[Keys]; // If the above had worked, these would be: `'Apple'|'Orange'|2|3`
type StrVals = Extract<Values, string>; // just the enum keys. Theoretically. `'Apple'|'Orange'`

playground

Upvotes: 0

Views: 239

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250336

You are close with keyof Fruit. You don't want the keys of a member of the Fruit enum (which is what the Fruit type represents). You want the keys of the object containing the enum members:

enum Fruits {
    Apple = 2,
    Orange = 3,
}

type Keys = keyof typeof Fruits; 

Upvotes: 2

Related Questions