gpt4 book ai didi

typescript - 使用数字枚举创建 Typescript `Record<>` 类型

转载 作者:搜寻专家 更新时间:2023-10-30 20:54:28 25 4
gpt4 key购买 nike

在 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 产生以下错误:

类型“AxisLabel”不满足约束“string”。

可以创建同时使用数字和字符串作为其成员名称的 JS 对象。

我希望在 Typescript 中做同样的事情,但不求助于不安全的强制转换或类型转换。 如何在不使用字符串枚举、any 或类型转换的情况下在 Typescript 中创建数字枚举 Record<> 类型?

最佳答案

更新:TypeScript 2.9 added support对于 numbersymbol作为有效的键类型,因此上面的代码不再给出错误,并且这个答案不再是必需的,只要您使用的是 TypeScript 2.9 或更高版本。

对于 TypeScript 2.8 及以下版本:


不管你信不信,JavaScript 中的对象键总是strings (好的,或 Symbol s ),即使对于数组也是如此。当您将非字符串值作为键传递时,它会首先被强制转换为字符串。但是人们当然希望数字键有意义,尤其是对于数组。 TypeScript 有点反射(reflect)了这种不一致的理念:通常你只能指定字符串值键(例如在 mapped types 中,如 Record<K,V> )。当这些情况相互作用时,您会感到奇怪。

这是我有时做的一件事:使用以下元组类型显式表示从数字到字符串的强制转换:

export type NumericStrings = ["0","1","2","3","4","5","6","7","8","9","10"] // etc

请注意,您可以根据需要扩展它。然后,您可以使用 lookup types将数字类型转换为其对应的字符串以用于映射类型。像这样:

export enum AxisLabel { X, Y }

// note the key is NumericStrings[AxisLabel], not AxisLabel
export const labelLookup: Record<NumericStrings[AxisLabel], string> = {
[AxisLabel.X]: "X axis",
[AxisLabel.Y]: "Y Axis"
};

这没有错误。如果您检查 labelLookup 的类型, 它显示为 Record<"0" | "1", string> .当您尝试索引到 labelLookup 时,会发生以下大多数情况下发生的事情:

labelLookup[AxisLabel.X]; // okay
labelLookup[0]; // okay
labelLookup["0"]; // also okay

labelLookup[10]; // error
labelLookup.X; //error

希望对您有所帮助;祝你好运!

关于typescript - 使用数字枚举创建 Typescript `Record<>` 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47776364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com