Issue
i am new to typescript and i am getting the error
"type Item[] | undefined is not assignable to Item[] type"
below is the code,
function Parent ({Items}: Props) {
return (
<Child subItems={Items.subItems}/> //error here
);
}
function Child({subItems}: Item[]) {
const sortedSubItems = subItems.sort((a: Item,b: Item) => b.createdAt.localeCompare(a.createdAt));
return (
<>
{sortedSubItems.map((subItem: Item) => {
return (
<Card key={subItem.id}>
<CardHeader>
{subItem.name}
</CardHeader>
</Card>
);
})}
</>
);
};
here subItems has structure like below,
const subItems = [
{
id: '1',
title: 'subitem-one',
status: 'new',
createdAt: '2020-08-13T16:32:10.000Z',
orders: [
{
id: '1',
title: 'subitem1-order-one',
status: 'new',
},
{
id: '2',
title: 'subitem1-order-two',
status: 'new',
},
]
},
{
id: '2',
title: 'subitem-two',
status: 'new',
createdAt: '2020-08-16T12:02:06.000Z',
orders: [
{
id: '2',
title: 'subitem2-order-one',
status: 'new',
},
],
},
]
and the Item type is like below,
export interface Item {
id: string;
createdAt: string;
name?: string;
orders?: Order[];
subItems?: Item[];
}
could someone help me fix the error using typescript and react. thanks.
Solution
Because you have an optional type operator(the question mark) on your subItems property, that indicates to Typescript that that property can be undefined. You will need to type the subItems prop for your Child component to reflect that, and handle it appropriately in the code:
interface ChildProps {
subItems?: Item[]
}
function Child({subItems}: ChildProps) {
const sortedSubItems = subItems ? subItems.sort((a: Item,b: Item) => b.createdAt.localeCompare(a.createdAt)) : [];
return (
<>
{sortedSubItems.map((subItem: Item) => {
return (
<Card key={subItem.id}>
<CardHeader>
{subItem.name}
</CardHeader>
</Card>
);
})}
</>
);
};
Answered By - Chris B.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.