【发布时间】:2018-05-26 08:37:44
【问题描述】:
在 Typescript 中,可以使用字符串枚举创建记录类型:
enum AxisLabel { X = "X", Y = "Y" }
export const labelLookup: Record<AxisLabel, string> = {
[AxisLabel.X]: "X axis",
[AxisLabel.Y]: "Y Axis"
};
我需要创建一个类似于上述对象的Record 对象,但我不希望使用字符串枚举。
当我尝试这样的事情时:
enum AxisLabel { X, Y }
export const labelLookup: Record<AxisLabel, string> = {
[AxisLabel.X]: "X axis",
[AxisLabel.Y]: "Y Axis"
};
Typescript 产生以下错误:
Type 'AxisLabel' does not satisfy the constraint 'string'.
可以用数字和字符串作为成员名来创建JS对象。
我希望在 Typescript 中做同样的事情,但不使用不安全的强制转换或类型转换。 如何在 Typescript 中创建数字枚举 Record 类型而不使用字符串枚举、any 或类型转换?
【问题讨论】:
标签: typescript enums