Peter Boomsma
Peter Boomsma

Reputation: 9836

How to assign a Type to a prop?

I have a parent component:

// DashboardComponent.tsx

const DashboardComponent = () => {
  const {loading, error, data} = useQuery(resolvers.ReturnAllMovies);

  if (loading) return <p>loading</p>;
  if (error) return <p>Error! ${error.message}</p>;

  const movies: IMovie[] = data.movies;

  return (
    <React.Fragment>
      <DashboardMovieOverviewMenu />
      { movies.length > 0 ? <MovieOverview movies={movies} /> : null }
    </React.Fragment>
  );
};

And a child component:

// MovieOverview.tsx

const MovieOverview = (props: IMovie[]) => {
  const movies = props;

  ...
}

In the parent component I declare the const movies to of a type IMovie and it's an array:

enter image description here

In the child component I declare the prop to be of type IMovie and array:

enter image description here

But the parent component is showing an error:

Type '{ movies: IMovie[]; }' is missing the following properties from type 'Pick<IMovie[], keyof IMovie[]>': [Symbol.iterator], [Symbol.unscopables], map, filter, and 26 more.

Upvotes: 0

Views: 71

Answers (2)

When you do (props: IMovie[]) you're actually saying that the whole prop object is an array of IMovies. In order to type a prop there are a couple different ways, here are two:

  1. const MovieOverview = (props: {movie:IMovie[]}) => {
interface Props {
    movies: IMovie[]
}
    
const MovieOverview = (props: Props) => { 
    const movies = props;
    ...
}

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 371138

The argument passed to functional components is an object, which contains keys corresponding to prop names, and their corresponding values. The array of movies is not the props argument, but nested inside as props.movies.

This

const movies = props;

needs to be

const { movies } = props;

or

const movies = props.movies

or use

const MovieOverview = ({ movies }) => {

Upvotes: 0

Related Questions