【问题标题】:(TypeScript2) How do you loop through an array of interface type?(TypeScript2)如何循环访问接口类型数组?
【发布时间】:2016-12-15 11:38:40
【问题描述】:

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

下面是我正在使用的代码。当尝试访问在接口上定义为字符串的 mapping.attribute 时,我收到错误 [Property '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 循环,以便我可以使用已在我的接口中定义的属性?

【问题讨论】:

    标签: typescript typescript2.0


    【解决方案1】:

    替换时我能够运行您的示例

    for (let mapping in mappings) {
    

    for (let mapping of mappings) {
    

    【讨论】:

      【解决方案2】:

      这是由于 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"
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-29
        • 2019-12-02
        • 1970-01-01
        • 1970-01-01
        • 2022-09-22
        • 2017-12-05
        • 2010-10-13
        • 1970-01-01
        相关资源
        最近更新 更多