代码:
interface Interface {
[id: string]: Interface2;
}
interface Interface2 {
[id: string]: string|boolean;
}
var a:Interface = {
abc: {
a: 'a',
b: 'b',
c: 'c'
},
cde: {
c: 'c',
d: 'd',
e: true
}
};
if (a.cde.e) {
console.log(1);
} else {
console.log(2);
}
if (a['cde']['e']) {
console.log(1);
} else {
console.log(2);
}
在底部,您可以看到两个条件。
在第一个条件下,编译器给出一个错误:
类型“Interface”上不存在属性“cde”。
在第二个条件下 - 没有错误。
为什么编译器在第一个条件下会提示? 我该如何解决这个问题?
您可以在这里尝试 www.typescriptlang.org/Playground
最佳答案
将[id: string]: Interface2;
视为字典
。字典保存数据,键也是数据的一部分。为了拥有强类型接口(interface)并能够访问它的属性,您可以直接向接口(interface)添加属性:
interface Interface3 {
abc: Interface2;
cde: Interface2;
}
在所有其他情况下,您将使用动态属性,例如使用 any
类型:
var c: any = a;
if (c.cde.e) {
console.log(1);
}
或使用括号表示法
a['cde']['e']
关于javascript - Typescript:为什么当使用 [id: string]: any 描述接口(interface)中的对象时出现错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32054588/