TypeScript error: Type 'IStory | undefined' is not assignable to type

Viewed 174

I'm using dynamic routing. I get id: string with useParams then I loop through array of posts to find target post and change type of id to Number otherwise I get an error. The problem happens when I assign type IStory to targetStory. It says:

Type 'IStory | undefined' is not assignable to type 'IStory'. Type 'undefined' is not assignable to type 'IStory'.

I do not know how to fix that. Could you help me please?

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>
  );
};
1 Answers

It's because Array.find() could possibly return undefined if it fails to find any item

You could have a fallback to your find condition and cast it like so:

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