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;
};
这有助于解释密钥应该是什么。例如:
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;
};