I am new to next.js and typescript and I encountered a typescript error in vscode. Even though it does not impact the state variable, I am curious to understand why the error occurs and how to resolve it
Error message: "Argument of type 'Movie | undefined' is not assignable to parameter of type 'SetStateAction<Movie | null>'. Type 'undefined' is not assignable to type 'SetStateAction<Movie | null>'"
Tsx snippet:
import { useEffect, useState } from "react";
import { Movie } from "typings";
interface Props {
netflixOriginals: Movie[];
}
export default function Banner({ netflixOriginals }: Props) {
const [movie, setMovie] = useState<Movie | null>(null);
useEffect(() => {
setMovie(
netflixOriginals[Math.floor(Math.random() * netflixOriginals.length)]
);
}, [netflixOriginals]);
console.log(movie);
This line triggers the error when setting state:
netflixOriginals[Math.floor(Math.random() * netflixOriginals.length)]
typings file:
export interface Movie {
title: string
backdrop_path: string
media_type?: string
release_date?: string
first_air_date: string
genre_ids: number[]
id: number
name: string
origin_country: string[]
original_language: string
original_name: string
overview: string
popularity: number
poster_path: string
vote_average: number
vote_count: number
}
When console logging the state, it retrieves a random item from the list. I am interested in learning how to correctly handle this according to typescript rules.
I understand that if the array were empty, it would result in an 'undefined' value, but I can ensure that it always contains elements from the parent component. How can I specify to typescript that it will always return a 'Movie' type