提供 const 变量接口时出现打字稿错误

时间:2021-05-26 13:14:07

标签: typescript

 const feedingItem: Notification = feedingPageNotifications.find(
    (notification: Notification) => notification.id === index
  )
export interface Notification {
  priority: number
  id: number
  title: string
  description: string
  buttonText: string
  backgroundImage: number
  displayName?: boolean
  backgroundColor: string
}

feedingItem 正在做我想做的事情,例如,我可以输入 feedItem.title,它会自动完成并进行类型检查,但由于某种原因,我在 const feedItem 下方出现错误,说:

Type '{ priority: number; id: number; title: string; description: string; buttonText: string; backgroundColor: string; backgroundImage: any; displayName?: undefined; } | { priority: number; id: number; ... 5 more ...; backgroundImage: any; } | undefined' is not assignable to type 'Notification'.
  Type 'undefined' is not assignable to type 'Notification'.ts(2322)

这个错误的原因是什么?

1 个答案:

答案 0 :(得分:0)

让我们看看 Array.find 的类型签名,它看起来像这样:

find(
  predicate: (value: T, index: number, obj: T[]) => unknown,
  thisArg?: any
): T | undefined;

如您所见,它返回 T | undefined。这是因为数组中可能没有任何项与您提供给 find 的谓词匹配。