用Typescript声明和初始化一个字典 [英] Declare and initialize a Dictionary in Typescript
本文介绍了用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版本)。 I
在VS中得到这些错误,正如你所料:索引签名是
不兼容。键入'{firstName:string; }'不能分配键入
'IPerson'。类型{firstName:
string;中缺少属性'lastName' }'。
显然这在传递初始数据在声明。
我猜这是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屋!
查看全文