How to create a union type from Enum values in TypeScript?
I have the following enum, (could be const or not) I would like to derive an union type, similarly at what I have hardcoded as MyNewOne
. How to do it with latest TS?
const enum FieldId {
Code = 'code',
Title = 'title',
Statuses = 'statuses',
}
type MyNewOne = 'code' | 'title' | 'statuses'
The first point I would like to make is. Are you sure this is what you want? The whole point of enums is to use the enum members rather than use the strings. You can't even assign a raw string to an enum member, even if it's type is provably one of the members:
const enum FieldId {
Code = 'code',
Title = 'title',
Statuses = 'statuses',
}
let enumValue:FieldId = 'code'; // error
Playground Link
Also I would like to point out that the type FieldId
is already a union, a union of the enum members. So type FieldId = FieldId.Code | FieldId.Title | FieldId.Statuses
(this is born out if you use it with Exclude
for example and try to exclude one member ex)
That being said, we can trick the compiler into converting the enum to a string, by inserting it in a template literal type:
const enum FieldId {
Code = 'code',
Title = 'title',
Statuses = 'statuses',
}
type FieldIdValue = `${FieldId}` // "code" | "title" | "statuses"
let v:FieldIdValue = "code"
let vBad: FieldIdValue = "" //err
Playground Link
Use mapped types
const enum FieldId {
Code = 'code',
Title = 'title',
Statuses = 'statuses',
}
type ToUnion<T extends Record<string, string | number>> = keyof {
[Prop in keyof T as `${T[Prop]}`]: Prop
}
type Result = ToUnion<typeof FieldId>
Playground