【发布时间】:2021-01-26 06:33:47
【问题描述】:
我正在尝试缩小(通过推断)我想要从此数组过滤器中删除的类型,但它给了我一个 TypeError: 'Item' is missing the following properties
type ItemList = (Item | ItemGroup )[];
type ItemGroup = {
name: string;
items: Item[];
}
type Item = {
key: string;
label: string;
}
const list: ItemList = [
{
key: 'key',
label: 'label'
},
{
name: 'name',
items: [
{
key: 'key1',
label: 'label2'
},
{
key: 'key3',
label: 'label4'
},
]
}
]
const groups: ItemGroup[] = list.filter( l => 'name' in l )
^^^^^^
// Type '(Item | ItemGroup)[]' is not assignable to type 'ItemGroup[]'.
// Type 'Item | ItemGroup' is not assignable to type 'ItemGroup'.
// Type 'Item' is missing the following properties from type 'ItemGroup': name, items ts(2322)
有什么想法吗?
【问题讨论】:
-
看起来
groups应该输入为ItemList,因为filter返回一个数组。错误消息实际上告诉您问题所在:您的ItemGroup没有name。 -
对不起,我在写问题时错过了输入,它应该是
ItemGroup[](现在更新)
标签: typescript types typescript-typings union-types