typescripttypescript3.0

Type of enum values


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"

Solution

  • 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)