gpt4 book ai didi

typescript 错误 : Type 'IStory | undefined' is not assignable to type

转载 作者:行者123 更新时间:2023-12-05 02:39:40 24 4
gpt4 key购买 nike

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

Type 'IStory | undefined' is not assignable to type 'IStory'. Type'undefined' is not assignable to type '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>
);
};

最佳答案

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

您可以对您的查找条件进行回退并像这样转换它:

const targetStory: IStory = storyList.find((story) => story.id === Number(id)) {} as IStory;

关于 typescript 错误 : Type 'IStory | undefined' is not assignable to type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68993651/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com