Home > Blockchain >  How to re-use type in React & TS application
How to re-use type in React & TS application

Time:05-23

I am making application in React & TS and trying to do my best to improve code (re-use type).

I have type:

export type Book = {
    author: string
    title: string
}

Now I have 2 components which I am using this type.

In the first component, my compiler does not see any problems. (books.data - array of object with type Book)

<BookContent>
  {books.data.map((book: Book) => {
    return <SingleBook key={book.id} book={book} />;
  })}
</BookContent>;

But in SingleBook component I am getting error type in props: Property 'book' does not exist on type 'Book'.ts(2339)

export const SingleBook = ({ book }: Book) => {
  return <SingleBookContainer>...restOfCode</SingleBookContainer>;
};

What should I do to solve this problem?

EDIT:

(property) book: Book
Type '{ key: number; book: Book; }' is not assignable to type 'IntrinsicAttributes & Book'.
  Property 'book' does not exist on type 'IntrinsicAttributes & Book'.ts(2322)

CodePudding user response:

Because you are destructuring props and type it as Book

1st solution

export const SingleBook = ({ book }: { book: Book }) => {
  return <SingleBookContainer>...restOfCode</SingleBookContainer>;
};

2nd solution

type Props = {
  book: Book
}

export const SingleBook = ({ book }: Props) => {
  return <SingleBookContainer>...restOfCode</SingleBookContainer>;
};

  • Related