1

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

1 Answer 1

5

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;
   ...
} 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.