(TypeScript2)如何遍历接口类型数组?

时间:2016-12-15 11:38:40

标签: typescript typescript2.0

使用for循环时,let对象具有字符串类型,即使我迭代的对象是接口中定义的类型。

以下是我正在使用的代码。当尝试访问作为字符串在接口上定义的mapping.attribute时,我收到错误[Property'属性'类型'字符串'。

上不存在

我有以下界面和功能:

interface IMapping {
    attribute: string;
    property: string;
}

mapAttributes(mappings: IMapping[], values) {            
    for (let mapping in mappings) {
        if (mapping.hasOwnProperty("attribute")) {
            console.log(this.attributes.find(attribute => attribute.name === mapping.attribute).value);
        }
    }
}

如何定义for循环以便我可以使用在我的界面中定义的属性?

2 个答案:

答案 0 :(得分:13)

我可以在替换

时运行您的示例
for (let mapping in mappings) {

for (let mapping of mappings) {

答案 1 :(得分:1)

这是由于 for..of与for..in语句

for..of和for..in语句都在列表上进行迭代;迭代的值虽然不同,但 for..in 返回要迭代的对象上的键的列表,而 for..of 返回数字值的列表被迭代对象的属性。

以下是展示这种区别的示例:

let list = [4, 5, 6];

for (let i in list) {
   console.log(i); // "0", "1", "2",
}

for (let i of list) {
   console.log(i); // "4", "5", "6"
}
相关问题