Michael Durrant
Michael Durrant

Reputation: 96484

How to use an array for a parameter in typescript? Cannot find name 'array' (React)

I am learning Typescript and I am changing existing files in a React app from js to tsx.

For the code below I pass in an array of posts.

I've change the file extension to .tsx and I then change the signature from

export default function PostList ({ posts = [] }) {

to

export default function PostList ({ posts = [] }: { posts: array}) {

but I get

TypeScript error: Cannot find name 'array'.  TS2304

Rest of the code:

import React from 'react'
import Post from './Post'

export default function PostList ({ posts = [] }: { posts: array}) {
  const sortedPosts = posts.sort((postA,postB) => {
    return Date.parse(postB.created) - Date.parse(postA.created);
  })
  
  return (
    <div>
      {sortedPosts.map((p, i) => (
        <React.Fragment key={'post-' + i}>
          <Post {...p} />
          <hr />
        </React.Fragment>
      ))}
    </div>
  )
}

Upvotes: 1

Views: 893

Answers (1)

Olga
Olga

Reputation: 217

Array types can be written in one of two ways. In the first, you use the type of the elements followed by [] to denote an array of that element type:

const numbers: number[] = [1, 2, 3];

The second way uses a generic array type, Array<elemType>:

const numbers: Array<number> = [1, 2, 3];

Take a look at the documentation here.

In your case, posts can be described like:

posts: Post[]

where Post interface has to be defined like:

interface Post {
   id: number;
   ...
} 

Upvotes: 5

Related Questions