Skip to content
ClapelloNotes by Barath
ReactCh 17 · 1/6
Core7 min readUpdated

React / 94

React with TypeScript: typing props

TL;DR

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-ts

It's the same Vite project you know, with three differences:

What changes
FilesComponents are .tsx (TypeScript with JSX). Plain code is .ts.
Configtsconfig.json points to tsconfig.app.json (your src/ code) and tsconfig.node.json (config files like vite.config.ts)
Buildnpm 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:

PriceTag.tsx
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} />
no complaints · builds · ships

customer sees

: ₹120.00

The name is missing. Nobody knows until someone reports it.

PriceTag.tsx

TypeScript

you write

<PriceTag lable="Masala dosa" price={120} />
instantly, in your editor

error TS2322

Property 'lable' does not exist on type 'IntrinsicAttributes & PriceTagProps'. Did you mean 'label'?

fix one letter

customer sees

Masala dosa: ₹120.00
Same typo, two outcomes. JavaScript runs it and shows a blank label to a customer. TypeScript underlines it in your editor before you even save.

An 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 interface
typeinterface
Object shapes (props)yesyes
Unions like "sm" | "lg"yesno
Add fields by declaring it againnoyes (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

Card.tsx
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:

Alert.tsx
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:

Button.tsx
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.