给出以下代码
interface IPerson {
firstName: string;
lastName: string;
}
var persons: { [id: string]: IPerson; } = {
"p1": { firstName: "F1", lastName: "L1" },
"p2": { firstName: "F2" }
};
为什么初始化没有被拒绝?毕竟,第二个对象没有“lastName”属性。
Edit:此问题已在最新 TS 版本中得到修复。引用 @Simon_Weaver 对 OP 帖子的评论:
注意:此问题现已修复(不确定具体的 TS 版本)。我
正如你所期望的,在 VS 中得到这些错误:Index signatures are
incompatible. Type '{ firstName: string; }' is not assignable to type
'IPerson'. Property 'lastName' is missing in type '{ firstName:
string; }'.
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.
您可以通过在声明和初始化中拆分示例来使用类型化字典,例如:
var persons: { [id: string] : IPerson; } = {};
persons["p1"] = { firstName: "F1", lastName: "L1" };
persons["p2"] = { firstName: "F2" }; // will result in an error
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)