如何从枚举中获取联合类型的字符串值?

Joj*_*oji 2 typescript

我有一个enum这样的

enum A {
  Car = "car",
  Bike = "bike",
  Truck = "truck"
}
Run Code Online (Sandbox Code Playgroud)

我想要得到一个类型car | bike | truck

我知道这keof typeof A可以给我Car | Bike | Truck,但我需要这里的值而不是键。

und*_*ned 6

不幸的是,据我所知,您在这里尝试做的事情不可能用枚举来实现。

如果您不必使用enum则可以通过使用对象来保存类型的值并使用const 断言(仅当您使用 TypeScript 3.4+ 时)来解决此问题,以根据键和值创建类型它充当类似枚举的类型。

例子:

const A = {
  Car: "car",
  Bike: "bike",
  Truck: "truck",
} as const;

type A = typeof A[keyof typeof A];

const x: A = A.Bike; // A.Car, A.Bike, A.Truck
const y: A = "bike" // "car", "bike", "truck"
Run Code Online (Sandbox Code Playgroud)