我有一个片段
export type MyFragment = {
__typename?: "MyFragment"
age: string
friends?: Array<{
id: string
}> | null
}
但是当我像这样导出这个类型时:type Friends = MyFragment["friends"]
然后利用它
const MyComponent = (friends: Friends) => {
return (
{friends.map(friend) => <div>{friend.id}</div>}
)
}
它说id
不存在于friend
上,当我将鼠标悬停在friend上时,它认为这是一个数组,并列出了所有数组选项
1条答案
按热度按时间cngwdvgl1#
要简化问题,请执行以下操作:
你说的是
MyFragment.friends
,即类型Friends
可以是undefined
(通过?
),null
(通过| null
)如果值是
undefined
或null
,则不能Map它,因此数组的union类型会出现类型错误,undefined或null。如果你想在运行时得到一个空数组,可以使用空合并:
或者,要使
Friends
类型别名永远不会是null
或undefined
,请使用NonNullable
实用程序类型:这样就不需要修改函数/组件了(当然,也不能将
null
或undefined
传递给需要NonNullable
Friends
的函数)。