jumbopap
jumbopap

Reputation: 4137

Getting a union type with all string enum values

I have an example enum that looks like:

enum MyEnum {
    foo = "Lorem",
    bar = "Ipsem",
}

How can I get a union type that looks like Lorem | Ipsem from that enum?

I would like to be able to safely run functions based on string in runtime, like:

type myType = "Lorem" | "Ipsum";
const doStuff = (s: myType) => {
    return "foo";
};

doStuff("Lorem");

Except derived from the enum values.

Upvotes: 2

Views: 1383

Answers (2)

Arnaud Leymet
Arnaud Leymet

Reputation: 6122

The list of values of an enum can be infered as a type with some help of the template literal operator:

enum MyEnum {
    foo = "Lorem",
    bar = "Ipsem",
}

type MyEnumValue = `${MyEnum}`
// => type MyEnumValue = "Lorem" | "Ipsem"

const values: MyEnumValue[] = Object.values(MyEnum)
// => ["Lorem", "Ipsem"]

Reference article: Get the values of an enum dynamically (disclaimer: author here)

Upvotes: 0

Matt McCutchen
Matt McCutchen

Reputation: 30889

I'm not aware of any way to get at the string literal type underlying an enum literal type. Your best option may be to use a namespace instead of an enum:

namespace MyEnum {
  export const foo = "Lorem";
  export const bar = "Ipsem";
}
type MyEnum = (typeof MyEnum)[keyof typeof MyEnum];

For additional background, see this thread.

Upvotes: 2

Related Questions