Sub topic 9
Describing Props with TypeScript
This chapter assumes you can write function components, destructure props, and run a React project with TypeScript, for example a Vite react-ts template. Files that contain JSX use the .tsx extension.
Why type props
Props are the contract between a parent and a child. In plain JavaScript, a missing or misspelled prop shows up as undefined at runtime. In TypeScript, you describe the contract once, and the compiler checks every place the component is used.
Writing a props type
Declare a type (or interface) and annotate the destructured parameter with it.
type ButtonProps = {
label: string;
variant?: 'primary' | 'secondary';
onClick: () => void;
};
function Button({ label, variant = 'primary', onClick }: ButtonProps) {
return (
<button className={variant} onClick={onClick}>
{label}
</button>
);
}
export default function App() {
return <Button label="Save" onClick={() => console.log('saved')} />;
}Three things happen here:
labelis required. Omitting it is a compile error.variant?is optional. Inside the component its type is'primary' | 'secondary' | undefined. The default value in the destructuring removes theundefined.variantis a union of string literals, sovariant="danger"is rejected.
Choosing types for common props
| Kind of value | Type |
|---|---|
| Text | `string` |
| Number or boolean | `number`, `boolean` |
| Object | A named type, such as `User` |
| Array | `User[]` |
| Function with no arguments | `() => void` |
| Function that sends a value up | `(id: number) => void` |
| Anything React can render | `ReactNode` |
Typing children
The children prop is typed like any other prop. Use ReactNode, which covers elements, strings, numbers, arrays, and null.
import type { ReactNode } from 'react';
type CardProps = {
title: string;
children: ReactNode;
};
function Card({ title, children }: CardProps) {
return (
<section className="card">
<h2>{title}</h2>
{children}
</section>
);
}
export default function App() {
return (
<Card title="Profile">
<p>Software engineer</p>
</Card>
);
}Slot props such as header or sidebar use ReactNode in the same way.
Typing callbacks
Write the full function signature so the compiler checks the arguments the child sends.
type LikeButtonProps = {
onLike: (postId: number) => void;
};
function LikeButton({ onLike }: LikeButtonProps) {
return <button onClick={() => onLike(42)}>Like</button>;
}A parent can pass a function that ignores arguments, such as () => {}. It cannot pass one that requires arguments the child never supplies.
Common errors
- Property is missing in type. The parent left out a required prop. Pass it, or mark it optional with
?if that is the real intent. - Type is not assignable to the literal union. A variable declared with
let v = 'primary'has typestring, not'primary'. Declare it withconst, or annotate its type. - Object is possibly undefined. An optional prop has no default. Add a default in the destructuring or handle
undefinedexplicitly. - Overusing
any. It turns off the check that makes the props type useful. Useunknownor a specific type instead.
Exercise
A component has the props type { title: string; count?: number }. What is the type of count inside the component if you destructure it without a default, and how do you make it always a number?
Show answer
Its type is number | undefined. Add a default in the destructuring, for example { title, count = 0 }: Props, and count becomes number.
Exercise
Why does <Button label="Save" variant="danger" onClick={save} /> fail to compile with the ButtonProps type from this chapter?
Show answer
variant is typed as 'primary' | 'secondary'. The string "danger" is not part of that union, so the compiler rejects it.