属性 'forEach' 在 Typescript 中的类型 XXX 上不存在

Property 'forEach' does not exist on type XXX in Typescript

我想在 Typescript 和 React 中使用 forEach() 生成 table 行的列表。使用下面的代码时,我得到 Property 'forEach' does not exist on type 。有谁知道如何解决这一问题?我不应该能够对人使用 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>
  );
}

你可以这样做:-

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 不是 return 新数组。在这里使用 map 而不是 forEach.

除了你的打字问题,我猜你想使用 array.map instead of 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

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