gpt4 book ai didi

typescript - 空对象的索引签名和记录之间的区别?

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

我无法弄清楚索引签名和记录类型之间的区别。有人可以解释差异以及何时使用其中一个与另一个吗?

具体来说,我希望定义一个对象的类型,该对象的键和值将具有随机字符串,这些字符串将被迭代。

有区别吗:

let objectVariable: Record<string, string> = {}

let objectVariable2: {[index: string]: string} = {}

最佳答案

Record 的定义是:

/**
* Construct a type with a set of properties K of type T
*/
type Record<K extends keyof any, T> = {
[P in K]: T;
};

当创建类似 type MyType = Record<string, string>; 的类型时, 内联 Record导致以下类型:

type MyType = {
[P in string]: string;
};

这是说在集合 string 中创建一个具有字符串属性名称的对象类型.自 string是无界的,字符串有无限的可能性(不像 "prop1" | "prop2" 这样的字符串文字类型的联合)...所以它描述的对象可以有任意数量的任意名称的属性,唯一的限制是属性必须有string 的类型.

所以是的,从类型检查的角度它基本上等同于没有映射类型的索引签名示例 ( { [index: string]: string; }

使用普通索引签名

使用 Record虽然这种方式有点奇怪,但很多人可能不明白发生了什么。当可以有任意数量的属性时,一种更常见的表达意图的方法是不使用映射类型:

type ObjectWithStringProperties = {
[index: string]: string;
};

这有一个额外的好处,可以帮助解释 key 应该是什么。例如:

type PersonsByName = {
[name: string]: Person;
};
const collection: PersonsByName = {};

请注意,以这种方式,类型是不同的,因为使用具有这种类型的对象的开发人员将在他们的编辑器中查看额外描述的键名称信息。

使用 Record

请注意 Record通常像下面这样使用:

type ThreeStringProps = Record<"prop1" | "prop2" | "prop3", string>;
// goes to...
type ThreeStringProps = { [P in "prop1" | "prop2" | "prop3"]: string; };
// goes to...
type ThreeStringProps = {
prop1: string;
prop2: string;
prop3: string;
};

关于typescript - 空对象的索引签名和记录之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54100025/

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