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

标签 typescript mapped-types index-signature

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

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

有区别吗:

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/

相关文章:

angular - d3 - 使用 nest/group 创建查找

angular - 如何在 typescript 中声明和处理 float 类型?

javascript - typescript 索引签名访问器

typescript - 关于带有类型推断的映射元组类型的问题

javascript - typescript 中具有某种类型的任何属性的通用类型

typescript - 如何在不打开界面的情况下设置索引签名

javascript - Angular:错误 TS2322:类型 'Observable<{}>' 不可分配...使用 share() 运算符

javascript - 在 Angular 2 中提交发布请求时的奇怪行为

typescript - 映射类型 : removing optional modifier

javascript - 在 TypeScript 中按值类型排除对象键