将字符串枚举类型转换为枚举值的联合类型

5 enums typescript

如何获得打字稿字符串枚举的联合类型?

enum MyEnum {
  A = 'a', // Values are different from keys, so keyof will not help here.
  B = 'b',
}
Run Code Online (Sandbox Code Playgroud)

给定一个像上面那样的枚举类型,我怎样才能得到联合类型“a” | “乙”?

小智 0

都很好

type enumValuesToUnion<T> = T extends `${infer R}` ? R :never

type enumValuesToUnion_<T> = `${T}`

type a = enumValuesToUnion<MyEnum>
type b = enumValuesToUnion_<MyEnum>
Run Code Online (Sandbox Code Playgroud)