devsner
devsner

Reputation: 399

How can I solve this error 'don't use object as a type'?

I do not understand this error message caused.

My component has two and one data array which has objects.

I got an error message 'Don't use object as a type. The object type is currently hard to use'.

How can i solve it ??

I attached the data which array has objects.

first.tsx...
import { dataList } from './xxx';
   // This dataList === 
export const dataList = [
  {
    id: 1,
    title: "text",
    hidden1: "text",
  },
  {
    id: 2,
    title: "text",
    hidden1: "text",
    hidden2: "text",
  },
  {
    id: 3,
    title: "text",
    hidden1: "text",
    hidden2: "text",
    hidden3: "text",
  },
];

const First = () => {
  return <Second data={dataList} />
}

second.tsx...
const Second = ({data} : { data:object[] } ) => {.    << here, "Don't use 'object' as a type.
  return <ul><li> {data.tag....blah blah} </li><ul>
}



error message :

Don't use `object` as a type. The `object` type is currently hard to use ([see this issue](https://github.com/microsoft/TypeScript/issues/21732)).
Consider using `Record<string, unknown>` instead, as it allows you to more easily inspect and use the keys  @typescript-eslint/ban-types

Upvotes: 5

Views: 13674

Answers (2)

Janos Vinceller
Janos Vinceller

Reputation: 1266

I did not try this with React, so a bit different code style here, but Typescript compiles this even without creating an interface:

const second = (data: Record<string, unknown>[]) => {
  return data
    .map(item =>
      Object.keys(item)
        .map(key => `key:${key} = value:${item[key]}`)
        .join(',')
    )
    .join(';');
};

I built in some mapping, but you could just return data too. Which of course would be useless, but it would compile.

This would compile too. Notice the array [] symbol in both solutions:

const second = (data: { [key: string]: unknown }[]) => {
  return data
    .map(item =>
      Object.keys(item)
        .map(key => `key:${key} = value:${item[key]}`)
        .join(',')
    )
    .join(';');
};

Upvotes: 0

yudhiesh
yudhiesh

Reputation: 6799

You need to be explicit with the type of the data being destructured here.

You can just create an interface of the data.

Edit: As your data has some optional parameters I updated the interface to reflect that.

interface IData {
    id: number;
    title: string;
    hidden1: string;
    hidden2?: string;
    hidden3?: string;
}

Then replace object[] with IData[]. So now you specify that this takes in an array of the IData interface.

const Second = ({ data } : { data:IData[] }) => {
  return <ul><li>{data}</li><ul>
}

Upvotes: 7

Related Questions