nekromenzer
nekromenzer

Reputation: 342

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)

Upvotes: 0

Views: 1246

Answers (2)

Sarun UK
Sarun UK

Reputation: 6766

Try this approach,

     export const Chart = ({ data }: {data: { date: string; books: number }[]}) => (
             <chart data={data}
               type="monotone"
              dataKey="reviews"
              stroke="#c80acc"
             activeDot={{ r: 8 }}
        /> );

Codesandbox - https://codesandbox.io/s/bold-moon-hr9ne?file=/src/App.tsx

Upvotes: 1

Viet
Viet

Reputation: 12807

You can declare like this:

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

Upvotes: 1

Related Questions