I'm building a game. It has a GameResult component:
export default function GameResult({
scoresData,
onPlayAgain,
time,
place,
}: GameResultProps) {
return (
<div className="c-game-result">
<Leaderboard scoresData={scoresData} />
<Stats time={time} place={place} />
<PlayAgain onClick={onPlayAgain} />
</div>
);
Here are the interfaces for props that its children have:
interface Props {
scoresData: string[];
}
interface Props {
time: string;
place: string;
}
interface Props {
onClick: React.MouseEventHandler<HTMLButtonElement>;
}
In the parent component, GameResult, I have GameResultProps that consists of all these interfaces:
interface GameResultProps {
scoresData: string[];
onPlayAgain: React.MouseEventHandler<HTMLButtonElement>;
time: string;
place: string;
}
My question is: How can I unify all child interfaces into a single props interface for a parent (GameResult), while keeping the interfaces separate for each child?
type GameResultProps = StatsProps & LeaderboardProps & PlayAgainProps
It works, however, it seems completely unmaintainable. I have to jump to three files in order to understand what props GameResult should accept. Is there a way to simplify it so that I can access all children props types (scoresData, onPlayAgain, time, place) right in the parent (GameResult) ?
You could use a type transformation:
In your GameResult component:
interface GameResultProps {
scoresData: string[];
onPlayAgain: React.MouseEventHandler<HTMLButtonElement>;
time: string;
place: string;
}
In Stats for example:
type PropsStats = Pick<GameResultProps, "time" | "place">;
Typescript Docs: Utility Types
However to keep it simple you could also just create one type file where you define all three types and combine them to a GameResultProps. Like you did in your post.