Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type of enum values [duplicate]

I can obtain a type representing the keys of an interface with:

interface I { a: string; b: string; }
const i: keyof I; // typeof i is "a" | "b"

Is there a way to similarly obtain a type representing the values of an enum?

enum E { A = "a", B = "b" }
const e: ?; // typeof e is "a" | "b"
like image 257
rid Avatar asked Mar 26 '26 16:03

rid


1 Answers

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

enum E { A = "a", B = "b" }

type EValue = `${E}`
// => type EValue = "a" | "b"

const value: EValue = "a" // => ✅ Valid
const valid: EValue = "b" // => ✅ Valid
const valid: EValue = "🤡" // => 🚨 Invalid

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

like image 56
Arnaud Leymet Avatar answered Mar 29 '26 10:03

Arnaud Leymet