React / 94
React with TypeScript: typing props
Start a TypeScript React project and describe each component's props, so typos and wrong values show up in your editor, not in front of users.
Start a TypeScript project
npm create vite@latest tasty-bites -- --template react-tsIt's the same Vite project you know, with three differences:
| What changes | |
|---|---|
| Files | Components are .tsx (TypeScript with JSX). Plain code is .ts. |
| Config | tsconfig.json points to tsconfig.app.json (your src/ code) and tsconfig.node.json (config files like vite.config.ts) |
| Build | npm run build runs tsc -b && vite build: type-check first, bundle second |
Adding TypeScript to an existing Vite project? Install typescript, @types/react and @types/react-dom as dev dependencies, add a tsconfig.json, and rename files to .tsx one at a time.
Typing props
Describe the props object with a type, then annotate the destructured parameter:
type PriceTagProps = {
label: string;
price: number;
currency?: string; // ? means optional
};
export function PriceTag({ label, price, currency = "₹" }: PriceTagProps) {
return (
<p>
{label}: {currency}
{price.toFixed(2)}
</p>
);
}Now every <PriceTag /> is checked. Leave out label, misspell it, or pass price="120", and you get a red underline before you even save:
PriceTag.jsx
JavaScript
you write
<PriceTag lable="Masala dosa" price={120} />customer sees
: ₹120.00The name is missing. Nobody knows until someone reports it.
PriceTag.tsx
TypeScript
you write
<PriceTag lable="Masala dosa" price={120} />error TS2322
Property 'lable' does not exist on type 'IntrinsicAttributes & PriceTagProps'. Did you mean 'label'?
customer sees
Masala dosa: ₹120.00An optional prop (currency?) may be left out. Inside the component its type is string | undefined, so give it a default while destructuring, as above, or check it before use.
type or interface?
Both describe props, and both work:
type CardProps = { title: string }; // a type alias
interface CardProps2 { title: string } // an interfacetype | interface | |
|---|---|---|
| Object shapes (props) | yes | yes |
Unions like "sm" | "lg" | yes | no |
| Add fields by declaring it again | no | yes (declaration merging) |
For props the difference rarely matters. Pick one and stay consistent. This track uses type, because you'll need it for unions anyway.
Typing children
import type { ReactNode } from "react";
type CardProps = {
title: string;
children: ReactNode;
};
export function Card({ title, children }: CardProps) {
return (
<section>
<h2>{title}</h2>
{children}
</section>
);
}ReactNode means "anything React can render": JSX, strings, numbers, null, false, arrays of those. Use it for children almost always. ReactElement is narrower (JSX elements only, no plain text), and you can't use types to demand "only <li> children".
Props that depend on each other
Sometimes one prop only makes sense with another. An error alert needs a Retry handler; a success alert doesn't. A union of object types says exactly that:
type AlertProps =
| { kind: "success"; message: string }
| { kind: "error"; message: string; onRetry: () => void };
export function Alert(props: AlertProps) {
if (props.kind === "error") {
// TypeScript knows onRetry exists here
return (
<p role="alert">
{props.message}
<button type="button" onClick={props.onRetry}>Retry</button>
</p>
);
}
return <p role="status">{props.message}</p>;
}<Alert kind="error" message="Payment failed" /> is now an error: Property 'onRetry' is missing. The kind field tells the two shapes apart. Checking it narrows the type, so inside the if, props.onRetry is known to exist. (Don't destructure in the parameter here: narrowing works on props.kind.)
Extending a native element
A design-system Button should accept everything a real <button> does (disabled, aria-label, onClick, type…) plus your own props. Don't list them by hand. Borrow them:
import type { ComponentProps } from "react";
type ButtonProps = ComponentProps<"button"> & {
variant?: "primary" | "ghost";
};
export function Button({ variant = "primary", className = "", ...rest }: ButtonProps) {
return <button type="button" className={`btn btn-${variant} ${className}`} {...rest} />;
}ComponentProps<"button"> is every prop React's <button> accepts. & adds yours. You take out the props you handle and spread ...rest onto the real element. Because type="button" comes before the spread, a caller can still override it with type="submit". In React 19 this also passes ref through, since ref is a normal prop now.
The same trick works for any element (ComponentProps<"input">) or any component (ComponentProps<typeof Card>).
Why not React.FC?
Don't
Old style: React.FC
import type { FC } from "react";
const PriceTag: FC<PriceTagProps> = ({ label, price }) => {
// …
};Do
Today: a plain function with typed props
function PriceTag({ label, price }: PriceTagProps) {
// …
}FC isn't broken, but it adds nothing. Older tutorials used it because it once added children to every component automatically, even ones that ignored it. Since the React 18 types it doesn't, so you type children yourself either way. Plain functions are shorter, work with generic components (function List<T>(…)), and are what the React docs use.
Gotchas
Recall
Can you answer these?
0/5
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
