TypeScript 错误:输入 'ISory | undefined' 不可分配给类型

qwe*_*ezz 4 typescript

我正在使用动态路由。我得到 id: string 和 useParams 然后我循环遍历帖子数组以查找目标帖子并将 id 类型更改为 Number 否则我会收到错误。当我将类型 ISory 分配给 targetStory 时,会出现问题。它说:

输入“故事| undefined' 不能分配给类型'IStory'。类型“未定义”不可分配给类型“IStory”。

我不知道如何解决这个问题。请问你能帮帮我吗?

interface IStoryPageProps {
  id: string;
}

export interface IStory {
    by: string;
    descendants: number;
    id: number;
    kids: number[];
    score: number;
    time: number;
    date: string;
    title: string;
    type: string;
    url: string;
  }
  
const StoryPage: React.FC = () => {
  const { id } = useParams<IStoryPageProps>();

  const { storyList } = useTypedSelector((state) => state.story);

  // error happens here
  const targetStory: IStory = storyList.find((story) => story.id === Number(id));

  return (
    <section>
      <BackButton />
      <h1></h1>
    </section>
  );
};
Run Code Online (Sandbox Code Playgroud)

Rya*_* Le 5

这是因为Array.find()undefined如果找不到任何项目可能会返回

你可以有一个fallback你的查找条件并像这样投射它:

const targetStory: IStory = storyList.find((story) => story.id === Number(id)) {} as IStory;
Run Code Online (Sandbox Code Playgroud)