Search code examples
reactjstypestypeerrortypescript-typingsprop

How to defined correct data type for object


I'm passing this as my props

 export const LineChart = () => {
  const data = [
    {
      date: "2021/07/01",
      books: 10
    },
    {
      date: "2021/07/02",
      books: 25
    },
    {
      date: "2021/07/03",
      books: 15
    },
    {
      date: "2021/07/04",
      books: 48
    },
    {
      date: "2021/07/05",
      books: 102
    },
    {
      date: "2021/07/06",
      books: 59
    },
    {
      date: "2021/07/07",
      books: 37
    }
  ];
  return <Chart data={data} />;
};

And I'm receiving those data in my components as props

export const Chart = ({ data }:**type of data***) => (
    <chart
      data={data}
      type="monotone"
      dataKey="reviews"
      stroke="#c80acc"
      activeDot={{ r: 8 }}
    />  );

How we define the type of prop Data in typescript, I'm new to typescript, I'm receiving data as an object. datatype any works, but it's not proper type, How to define the data type of above object & get rid of type error,(code is working fine)


Solution

  • You can declare like this:

    { data }: {data: Array<{ date: string; books: number }>}