reactjs - cómo establecer el tipo de prop en react + typescript
Estudié React + TypeScript. Quiero establecer el tipo de propiedad de función de un componente. Pero no sé cómo configurarlo.
esto es código.
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>
);
};
No quiero poner "cualquier". ¿Qué tipo pongo?
Respuesta #1
Lo cambiaría para que estés pasando las props al componente de tarjeta que deseas usar en lugar de un objeto contenedor como prop. Eso también hace que la tipificación sea más sencilla. Así que puedes hacer esto:
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>
);
};
Respuesta #2
Simplemente actualiza el tipo así:
function MovieCard({ movie }: {movie: MovieProps })
