在 Typescript 中声明和初始化字典 [英] Declare and initialize a Dictionary in Typescript
问题描述
给定以下代码
interface IPerson {
firstName: string;
lastName: string;
}
var persons: { [id: string]: IPerson; } = {
"p1": { firstName: "F1", lastName: "L1" },
"p2": { firstName: "F2" }
};
为什么初始化没有被拒绝?毕竟,第二个对象没有lastName"属性.
Why isn't the initialization rejected? After all, the second object does not have the "lastName" property.
推荐答案
编辑:这个问题已经在最新的 TS 版本中得到修复.引用@Simon_Weaver 对 OP 帖子的评论:
Edit: This has since been fixed in the latest TS versions. Quoting @Simon_Weaver's comment on the OP's post:
注意:这已被修复(不确定哪个确切的 TS 版本).一世如您所料,在 VS 中得到这些错误:Index 签名是不相容.输入'{名:字符串;}' 不可分配给类型个人".类型{ firstName:"中缺少属性lastName":细绳;}'.
Note: this has since been fixed (not sure which exact TS version). I get these errors in VS, as you would expect:
Index signatures are incompatible. Type '{ firstName: string; }' is not assignable to type 'IPerson'. Property 'lastName' is missing in type '{ firstName: string; }'.
<小时>显然,在声明时传递初始数据时这不起作用.我猜这是 TypeScript 中的一个错误,所以你应该在项目站点上提出一个.
Apparently this doesn't work when passing the initial data at declaration. I guess this is a bug in TypeScript, so you should raise one at the project site.
您可以通过在声明和初始化中拆分示例来使用类型化字典,例如:
You can make use of the typed dictionary by splitting your example up in declaration and initialization, like:
var persons: { [id: string] : IPerson; } = {};
persons["p1"] = { firstName: "F1", lastName: "L1" };
persons["p2"] = { firstName: "F2" }; // will result in an error
这篇关于在 Typescript 中声明和初始化字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!