Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set prop type in react + typescript

i studied react + typescript. i want to set component function prop type. but i don't know how to set.

this is code.

interface MovieProps {
    id: number;
    title: string;
    year: number;
}

function App() {
  ...
  const movies: MovieProps[] = [
    { id:1, title: 'movie1', year: 2018 },
    { id:2, title: 'movie2', year: 2019 },
    { id:3, title: 'movie3', year: 2020 },
    { id:4, title: 'movie4', year: 2021 },
  ];
  const renderMovies: JSX.Element[] = movies.map(movie => {
    return (
      <MovieCard key={ movie['id'] } movie={ movie } />
    );
  });
    ...
}

function MovieCard({ movie }: any) {  <- this part
  return (
    <div className="movie">
      <div className="movie-title">{ movie['title'] }</div>
      <div className="movie-year">{ movie['year'] }</div>
    </div>
  );
};

i don't want to set "any". what i set type?

like image 683
khasui Avatar asked Jul 11 '26 11:07

khasui


2 Answers

I would change it so you are passing the props down to the card that you want to use instead of a container object as the prop. That makes the typing simpler too. So you can do this:

interface MovieProps {
    id: number;
    title: string;
    year: number;
}

function App() {
  ...
  const movies: MovieProps[] = [
    { id:1, title: 'movie1', year: 2018 },
    { id:2, title: 'movie2', year: 2019 },
    { id:3, title: 'movie3', year: 2020 },
    { id:4, title: 'movie4', year: 2021 },
  ];
  const renderMovies: JSX.Element[] = movies.map(movie => {
    return (
      <MovieCard key={ movie.id } {...movie} />
    );
  });
    ...
}

function MovieCard({ title, year }: MovieProps) {  <- this part
  return (
    <div className="movie">
      <div className="movie-title">{ title }</div>
      <div className="movie-year">{ year }</div>
    </div>
  );
};
like image 77
Cymen Avatar answered Jul 14 '26 06:07

Cymen


Just update type like this:

function MovieCard({ movie }: {movie: MovieProps })
like image 31
Viet Avatar answered Jul 14 '26 04:07

Viet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!