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

(TypeScript2) How do you loop through an array of interface type?

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

下面是我正在使用的代码。当尝试访问在接口上定义为字符串的 mapping.attribute 时,出现错误 [属性 'attribute' does not exist on type 'string'.]

我有以下接口和功能:

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 循环,以便我可以使用已在我的界面中定义的 属性?

我能够 运行 你的例子替换

for (let mapping in mappings) {

for (let mapping of mappings) {

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

for..of 和 for..in 语句都遍历 lists;迭代的值是不同的,for..in returns 被迭代对象上的键列表,而 for..of returns 正在迭代的对象的数字属性值列表。

下面是一个演示这种区别的示例:

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"
}