Home > Software design >  How to extract the type of enumerated value use typescript
How to extract the type of enumerated value use typescript

Time:08-19

enum code {
    a = 10,
    b = 20,
    c = "abc"
}

Now I have an enum value and I now want to get a union type

type IWantGet = 10 | 20 | 'abc'

Excuse me, do you have any good solutions?

CodePudding user response:

This will become possible in TypeScript 4.8 when the conversion of string literals to numbers is added.

type IWantGet = `${code}` extends infer U 
  ? U extends `${infer S extends number}` 
    ? S
    : U 
  : never

// type IWantGet = "abc" | 10 | 20

Playground


For now you can only have a union of string literal types.

type IWantGet = `${code}`
// type IWantGet = "10" | "20" | "abc"

Playground

  • Related