为什么typescript认为我的类型是一个数组,而它显然不是?

ktca8awb  于 2023-03-31  发布在  TypeScript
关注(0)|答案(1)|浏览(105)

我有一个片段

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上时,它认为这是一个数组,并列出了所有数组选项

cngwdvgl

cngwdvgl1#

要简化问题,请执行以下操作:

type MyFragment = {
  friends?: Array<{
    id: string
  }> | null
}
type Friends = MyFragment["friends"]

function f(friends: Friends) {
  return friends.map(f => f.id);
}

你说的是MyFragment.friends,即类型Friends可以是

  • x1m2 n1 × s的阵列,
  • undefined(通过?),
  • null(通过| null

如果值是undefinednull,则不能Map它,因此数组的union类型会出现类型错误,undefined或null。
如果你想在运行时得到一个空数组,可以使用空合并:

(friends ?? []).map(f => f.id)

或者,要使Friends类型别名永远不会是nullundefined,请使用NonNullable实用程序类型:

type Friends = NonNullable<MyFragment["friends"]>;

这样就不需要修改函数/组件了(当然,也不能将nullundefined传递给需要NonNullableFriends的函数)。

相关问题