I have an array of objects where the data is stored in an JSON file. Here is how the JSON file looks like:
[
{
"_id": "62bd5fba34a8f1c90303055c",
"index": 0,
"email": "[email protected]",
"nameList": [
{
"id": 0,
"name": "Wendi Mooney"
},
{
"id": 2,
"name": "Holloway Whitehead"
}
]
},
{
"_id": "62bd5fbac3e5a4fca5e85e81",
"index": 1,
"nameList": [
{
"id": 0,
"name": "Janine Barrett"
},
{
"id": 1,
"name": "Odonnell Savage"
},
{
"id": 2,
"name": "Patty Owen"
}
]
},
After that I have to use this object as props in another component (someComponent) and I made an interface:
interface Props {
data: [
{
_id: string;
index: number;
email: string;
nameList: { id: number; name: string };
}
];
}
Yet after that I get the current error:
Type '({ _id: string; index: number; nameList: { id: number; name: string; }[]; email?: undefined; } | { index: number; email: string; nameList: { id: number; name: string; }[]; _id?: undefined; } | { _id: string; index: number; email: string; nameList: ({ ...; } | ... 1 more ... | { ...; })[]; } | { ...; })[]' is not assignable to type '[{ _id: string; index: number; email: string; nameList: { id: number; name: string; }; }]'.
Target requires 1 element(s) but source may have fewer.ts(2322)
someComponent.tsx(3, 3): The expected type comes from property 'data' which is declared here on type 'IntrinsicAttributes & Props'
What may seem to be the problem?
CodePudding user response:
You specified data
on your Props
type but not for your input data object.
'data' is just the variable where I store the data so I dont pass in the properties on their own. data = {data}
data = {data}
- Here the data
should be specified with your data
type of Props
. If you haven't specified anything typescript will take its properties and creates an object. That is the reason you are getting the error.
Type '({ _id: string; index: number; nameList: { id: number; name: string; }[]; email?: undefined; } | { index: number; email: string; nameList: { id: number; name: string; }[]; _id?: undefined; } | { _id: string; index: number; email: string; nameList: ({ ...; } | ... 1 more ... | { ...; })[]; } | { ...; })[]' is not assignable to type '[{ _id: string; index: number; email: string; nameList: { id: number; name: string; }; }]'.
Provide a type for your input data or at least specify any
so that the error will be resolved.
Check this TS Playground