【发布时间】:2020-08-17 14:38:35
【问题描述】:
我是打字稿的新手,我遇到了错误
"type Item[] | undefined 不能赋值给 Item[] 类型"
下面是代码,
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>
);
})}
</>
);
};
这里的 subItems 具有如下结构,
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',
},
],
},
]
Item类型如下,
export interface Item {
id: string;
createdAt: string;
name?: string;
orders?: Order[];
subItems?: Item[];
}
有人可以帮助我使用打字稿修复错误并做出反应。谢谢。
【问题讨论】:
标签: reactjs typescript