jessica96
jessica96

Reputation: 85

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

I want to generate a list of table rows by using forEach() in Typescript and React. I get Property 'forEach' does not exist on type when using the code below. Does anyone know how to fix this? Shouldn't I be able to use forEach() on persons as it is an array of 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>
  );
}

Upvotes: 2

Views: 6006

Answers (3)

iosis555
iosis555

Reputation: 1

forEach is a method from JS Class Array, if you want to use it in a custom Class, it should inherit from Array or just be one (persons:Person[]), as suggested by Lakshya.

Upvotes: 0

ksav
ksav

Reputation: 20830

As well as your typing problem, I'm guessing you want to use 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

Upvotes: 1

Lakshya Thakur
Lakshya Thakur

Reputation: 8316

You can do something like this:-

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>
  );
}

Your persons variable was not a valid array object. You have sets its type to PersonList which itself is essentially a type. That's why you're getting Property 'forEach' doesn't exist on type.

One more thing, forEach doesn't return a new array. Use map here instead of forEach.

Upvotes: 4

Related Questions