【问题标题】:Property 'forEach' does not exist on type XXX in TypescriptTypescript 中的类型 XXX 上不存在属性“forEach”
【发布时间】:2020-11-01 19:45:45
【问题描述】:

我想在 Typescript 和 React 中使用 forEach() 生成表行列表。使用下面的代码时,我得到Property 'forEach' does not exist on type。有谁知道如何解决这一问题?我不应该能够对 Person 使用 forEach(),因为它是 PersonInterfaces 数组吗?

interface PersonList {
  [index: number]: PersonInterface
}

interface PersonInterface {
  name: string, 
  age: number
}

const persons:PersonList = [
  {
    name: 'John',
    age: 25,
  }, {
    name: 'Jill',
    age: 28,
  }
];

export default function Table() {
  return (
    <table>
      {
        persons.forEach(person => {
          return (
            <tr>
              <td>{person.name}</td>
            </tr>
          );
        })
        }
    </table>
  );
}

【问题讨论】:

    标签: reactjs typescript react-tsx


    【解决方案1】:

    你可以这样做:-

    interface Person {
      name: string, 
      age: number
    }
    
    const persons:Person[] = [
      {
        name: 'John',
        age: 25,
      }, {
        name: 'Jill',
        age: 28,
      }
    ];
    
    export default function Table() {
      return (
        <table>
          {
            persons.forEach(person => {
              return (
                <tr>
                  <td>{person.name}</td>
                </tr>
              );
            })
            }
        </table>
      );
    }
    

    您的 persons 变量不是有效的数组对象。您已将其类型设置为PersonList,它本身就是一种类型。这就是为什么你会收到Property 'forEach' doesn't exist on type

    还有一点,forEach 不会返回新数组。在这里使用map 而不是forEach

    【讨论】:

      【解决方案2】:

      除了您的打字问题,我猜您还想使用array.map 而不是array.forEach

      import React from 'react'
      
      interface PersonInterface {
        name: string
        age: number
      }
      
      const persons: PersonInterface[] = [
        {
          name: 'John',
          age: 25,
        },
        {
          name: 'Jill',
          age: 28,
        },
      ]
      
      const Table = () => {
        return (
          <table>
            {persons.map(person => (
              <tr>
                <td>{person.name}</td>
              </tr>
            ))}
          </table>
        )
      }
      
      export default Table
      

      【讨论】:

        【解决方案3】:

        forEach 是来自 JS 类 Array 的方法,如果你想在自定义类中使用它,它应该继承自 Array 或者只是一个(persons:Person[]),正如 Lakshya 所建议的那样。

        【讨论】:

        • 嗨。欢迎来到 SO。如果您可以提供代码 sn-p 来继承 Array,这可能是一个更好的答案。
        猜你喜欢
        • 2018-11-09
        • 2017-07-28
        • 2022-01-03
        • 2018-12-24
        • 2021-03-24
        • 2020-05-08
        • 2017-12-14
        • 2018-12-04
        • 2023-04-02
        相关资源
        最近更新 更多