In Typescript, it is possible to create record types with string enums:
enum AxisLabel { X = "X", Y = "Y" }
export const labelLookup: Record<AxisLabel, string> = {
[AxisLabel.X]: "X axis",
[AxisLabel.Y]: "Y Axis"
};
I need to create a Record
object similar to the one above, but I do not wish to use a string enum.
When I try something like this:
enum AxisLabel { X, Y }
export const labelLookup: Record<AxisLabel, string> = {
[AxisLabel.X]: "X axis",
[AxisLabel.Y]: "Y Axis"
};
Typescript produces the following error:
Type 'AxisLabel' does not satisfy the constraint 'string'.
It is possible to create JS objects with both numbers and strings as their member names.
I wish to do the same in Typescript, but without resorting to unsafe coercion or type casts. How do I do create numeric enum Record<> types in Typescript without using string enums, any
or type casts?
export const labelLookup: Record<AxisLabel, string> = { [AxisLabel.X]: 'X axis' }
Partial
:export const labelLookup: Partial<Record<AxisLabel, string>> = { [AxisLabel.X]: 'X axis' }