Skip to content
Tutorials Center
My learning

Topics

Lesson 93 of 132 ยท TypeScript with React

TypeScript and React

Start using TypeScript with React. Learn what types add, how to type props, children and events, how to read compiler errors, and which parts only exist before the code runs.

A React component is a function that takes props and returns UI. Nothing in plain JavaScript stops you from passing "twelve" where a number was expected, forgetting a required prop, or calling onSelect with the wrong arguments. You find out in the browser, sometimes only when a customer hits that code path. TypeScript moves that discovery to your editor: you describe the shape of your props, state and events once, and the compiler checks every use.

This lesson is a first practical tour. You will learn what TypeScript adds (and what it does not), how to type props, children and events, how to model props that depend on each other, and how to read the compiler's errors. We build on the language basics from the TypeScript tutorial but you can follow along knowing only simple types such as string, number and boolean. The next lessons go deeper: Typing State, Refs, Context and Reducers and Generic Components and Advanced Types.

Our live editor runs plain JavaScript with JSX; it does not understand type annotations. So all TypeScript code in this lesson is read-only (tsx blocks). The live examples show the runtime behaviour that each type is protecting you from, which is the best way to understand why the types exist.

Why TypeScript with React

  • Errors before the browser. Wrong prop names, missing props, wrong types and misspelled fields are underlined as you type.
  • Autocomplete that knows your components. Type <Avatar and the editor lists its props and their types. Rename a prop and the compiler finds every caller.
  • Documentation that cannot go stale. The type of a component's props is a contract that is checked, unlike a comment.
  • Safer refactoring. Change a data shape and the compiler lists every place that must change.
  • Confidence when working in teams. You can use a component written by a colleague without reading its source.

There are costs. You learn a second language layered on the first. Complicated types can become harder to read than the code itself. And, importantly, types give you no protection at runtime: they are erased when the code is built. Data that arrives from a server or a form is whatever it is, whatever your types claim. We come back to that below.

Setting up

The quickest way is a template. react-ts creates a Vite project with TypeScript already configured (read-only commands, since they need Node on your computer):

Terminal
npm create vite@latest my-app -- --template react-ts
cd my-app
npm install
npm run dev

Files that contain JSX end in .tsx; files with no JSX (utilities, hooks that return no JSX) end in .ts. Two tools work together and it helps to keep them apart:

  1. The compiler (tsc) checks types. npx tsc --noEmit reports errors and writes no files. Your editor runs the same checker as you type.
  2. The bundler (Vite, Next.js) removes types. Tools like esbuild, SWC or Babel simply delete the annotations and turn the JSX into JavaScript. They do not check types. So a project with type errors can still start in the dev server, which is why tsc --noEmit belongs in CI (Linting, Formatting and Code Quality).

The important compiler setting for React is "jsx": "react-jsx" in tsconfig.json. It tells TypeScript to use the modern JSX transform, so you do not need import React from 'react' at the top of each file. Also set "strict": true. Without it TypeScript quietly allows many mistakes.

Typing props

Props are an object, so you describe them as an object type. Either a type alias or an interface works; teams pick one and stay consistent. This lesson uses type.

TSX
type AvatarProps = {
  name: string;
  size?: number;          // optional: may be left out
  imageUrl: string | null; // required, but may be null
};

function Avatar({ name, size = 40, imageUrl }: AvatarProps) {
  return imageUrl ? (
    <img src={imageUrl} alt={name} width={size} height={size} />
  ) : (
    <span aria-label={name}>{name.charAt(0)}</span>
  );
}

Four details:

  • The annotation goes on the destructured parameter: { name, size = 40, imageUrl }: AvatarProps. You rarely write the return type; TypeScript infers JSX.Element (written React.JSX.Element in React 19's types) on its own.
  • size?: number means "may be omitted", so inside the function its type is number | undefined. A default value in the destructuring (size = 40) removes the undefined: size is a plain number in the body.
  • imageUrl: string | null is different from imageUrl?: string. The first must always be passed (even if it is null). The second can be left out. The difference matters at runtime too; see the live example below.
  • Function props describe their arguments and return value: onSelect: (id: number) => void.

Now the compiler enforces the contract. These calls would each be underlined in the editor, with the error that tsc prints:

TSX
<Avatar name="Ada" imageUrl={null} />        // fine
<Avatar imageUrl={null} />                   // error TS2741: Property 'name' is missing in type '{ imageUrl: null; }' but required in type 'AvatarProps'.
<Avatar name="Ada" size="large" imageUrl={null} />   // error TS2322: Type 'string' is not assignable to type 'number'.
<Avatar name="Ada" imageUrl={null} color="red" />    // error TS2322: Type '{ name: string; imageUrl: null; color: string; }' is not assignable to type 'IntrinsicAttributes & AvatarProps'.

Read these messages slowly; they are shorter than they look. The first: a required property is missing. The second: you gave a string where the type says number. The third: an object with an extra property (color) does not match, because AvatarProps has no color. Fix by editing either the caller or the type, whichever is wrong.

What a type protects you from

Here is a bug that types would have prevented. A price comes from a text input, so it is a string, and the code adds instead of multiplying or compares as text. In TypeScript the line total(priceFromInput, 3) would be an error before you ever ran it. In JavaScript it just runs:

The bug a type would have caught

The first row gives 45, the second gives 405, a string, because '40' + 5 joins the characters. No error, no warning, just a wrong total on the screen. With function addShipping(price: number, shipping: number): number, the second call is rejected by the compiler: Argument of type 'string' is not assignable to parameter of type 'number'. Types catch a whole class of "wrong kind of value" mistakes for free.

Optional, null and defaults at runtime

size?: number and imageUrl: string | null look similar but behave differently when the component runs. JavaScript only applies a default value when the prop is undefined, not when it is null. This is the reason the type says string | null when null is a meaningful value, and why you should not assume a default saves you from null.

undefined versus null in props

When the prop is omitted or explicitly undefined, the default ! is used and the greeting ends with an exclamation mark. With punctuation={null} the default is not applied, null renders as nothing, and the sentence has no ending. In TypeScript, punctuation?: string would reject null unless you wrote string | null, so this surprise is caught at the call site.

Typing children

Anything you put between a component's tags arrives as the children prop. The right type is almost always ReactNode: it covers everything React can render: strings, numbers, elements, arrays of those, null, undefined and booleans.

TSX
import type { ReactNode } from 'react';

type CardProps = {
  title: string;
  children: ReactNode;
};

function Card({ title, children }: CardProps) {
  return (
    <section>
      <h2>{title}</h2>
      {children}
    </section>
  );
}

import type imports only a type, so nothing is left in the compiled JavaScript. Related types you will see:

Type Accepts Use when
ReactNode Anything renderable, including text, null and arrays The default for children and "slots"
ReactElement Only a JSX element (<Foo />), not text or null You must receive exactly one element
string Only text The component formats or measures text itself
(value: T) => ReactNode A function that returns UI Render props (Render Props and HOCs)

Avoid typing children as JSX.Element unless you really require it: <Card>Some text</Card> would be an error. And avoid React.FC: it used to add an implicit children prop, which is no longer true, and it gets in the way of generics. Plain functions with a typed parameter are the standard.

The next demo shows why ReactNode has to be so wide. The component receives very different kinds of children and describes each one.

What children can be

Notice null and false count as zero rendered nodes, and "nothing" gives undefined. A type such as string would reject most of these, and ReactElement would reject text, null and arrays. That is why ReactNode is the right default.

Typing events

React wraps browser events in its own synthetic event types. TypeScript's React typings give them a generic parameter that says which element the handler is attached to: ChangeEvent<HTMLInputElement>, MouseEvent<HTMLButtonElement>, FormEvent<HTMLFormElement>, KeyboardEvent<HTMLInputElement>. The element type is what makes event.currentTarget.value or event.currentTarget.form known to the compiler.

TSX
import { useState } from 'react';
import type { ChangeEvent, FormEvent, MouseEvent } from 'react';

function SearchBox({ onSearch }: { onSearch: (query: string) => void }) {
  const [query, setQuery] = useState('');

  function handleChange(event: ChangeEvent<HTMLInputElement>) {
    setQuery(event.target.value);
  }

  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    onSearch(query);
  }

  function handleClear(event: MouseEvent<HTMLButtonElement>) {
    setQuery('');
    event.currentTarget.blur();
  }

  return (
    <form onSubmit={handleSubmit}>
      <input value={query} onChange={handleChange} />
      <button type="button" onClick={handleClear}>Clear</button>
    </form>
  );
}

You can skip the annotation when the handler is written inline, because TypeScript infers the event type from the JSX attribute:

TSX
<input value={query} onChange={(event) => setQuery(event.target.value)} />

Hover over event in your editor and you will see ChangeEvent<HTMLInputElement>. When you define the handler as a separate function, as above, you must write the type yourself, or use the handler type: const handleChange: React.ChangeEventHandler<HTMLInputElement> = (event) => { ... }.

target versus currentTarget

Two properties look alike and are typed differently. currentTarget is the element your handler is attached to, so its type is exactly the generic you gave (HTMLButtonElement). target is the element that was actually clicked, which could be any descendant, so TypeScript can only call it a generic EventTarget (or HTMLInputElement for ChangeEvent, where the input itself is the source). Watch the difference at runtime:

target versus currentTarget

Click on the word "text" and the log reads target: EM, currentTarget: BUTTON. Click the padding around the label and target is BUTTON itself. Because target can be any inner element, reading .value from it is usually wrong in a click handler; use currentTarget, which is guaranteed to be the button you attached the handler to. TypeScript's two different types encode exactly this rule.

Props that depend on each other

Real components often accept one of several shapes. A plain object type with two optional props allows nonsense combinations; a discriminated union says "either this set of props or that set".

TSX
type ActionProps =
  | { kind: 'link'; href: string; label: string }
  | { kind: 'button'; onPress: () => void; label: string };

function Action(props: ActionProps) {
  if (props.kind === 'link') {
    return <a href={props.href}>{props.label}</a>;
  }
  return (
    <button type="button" onClick={props.onPress}>
      {props.label}
    </button>
  );
}

<Action kind="link" href="/docs" label="Docs" />                // fine
<Action kind="button" onPress={() => {}} label="Save" />        // fine
<Action kind="link" onPress={() => {}} label="Oops" />          // error: 'onPress' does not exist in type ... / 'href' is missing

The shared field kind (the discriminant) lets TypeScript narrow the type: inside if (props.kind === 'link') it knows props.href exists, and after the if it knows props.onPress exists. This is the same idea as a checked switch, and you will use it again for reducer actions. Here is the runtime half. At runtime the types have vanished, so the component must do the check itself, and the check is what the compiler uses to narrow:

Narrowing a union at runtime

The last line is the mistake TypeScript would reject: it renders a link whose href is undefined, so the text reads "Oops (link to )" with an empty target. In JavaScript you notice that only if you look at the page. With the union type the call is underlined as soon as you type it.

More props you will type

TSX
import type { CSSProperties, ComponentProps } from 'react';

type BadgeProps = {
  tone: 'info' | 'success' | 'danger';   // a literal union: only these three strings
  style?: CSSProperties;                  // an inline style object
  items: readonly string[];               // you promise not to change the array
  onRemove?: (index: number) => void;     // optional callback
};

// Reuse the props of a native element instead of copying them:
type FancyButtonProps = ComponentProps<'button'> & { loading?: boolean };

A literal union such as 'info' | 'success' | 'danger' beats a plain string for variants: the editor suggests the valid values and a typo like 'dangr' is an error. ComponentProps<'button'> borrows every standard button prop (disabled, onClick, aria-label ...), which is how design-system buttons forward their props; the next lessons show it in depth.

Types stop at the edge of your program

Types describe what you promise a value looks like. They are checked against your own code, not against the world. When you write

TSX
const user = (await response.json()) as User;

you are telling the compiler "trust me". If the server sends something else, the compiler is happy and the app breaks at runtime anyway. Treat data from fetch, localStorage, URL parameters and form fields as unknown until you have checked it (by hand, or with a validation library such as Zod), and only then give it a precise type. Compare this with Data Fetching.

Avoid the two escape hatches unless you can say why: any switches checking off for that value (and spreads like a virus through everything it touches), and as casts overrule the compiler. A good rule is to prefer unknown over any, and a type guard or validation over as.

Common beginner errors

Situation What to do
Property 'x' does not exist on type 'Props' You used a prop that is not in the type. Add it, or fix the typo.
Type 'string | undefined' is not assignable to type 'string' The value may be missing. Handle undefined (default value, if, ??), do not cast it away.
Object is possibly 'null' after useRef or getElementById The element may not exist yet. Check for null first (useRef).
Parameter 'event' implicitly has an 'any' type A handler defined outside JSX needs an event type annotation.
Everything is any strict is off, or a library has no types. Turn on strict and install @types/... packages where needed.
Errors in node_modules Add "skipLibCheck": true to tsconfig.json.

When TypeScript is (and is not) worth it

Choose it for apps with several developers, long lifetimes, shared component libraries or complex data. Skip it, or start with JavaScript plus JSDoc, for throwaway prototypes and tiny demos like most examples on this site. Many teams adopt it gradually: rename one file at a time from .jsx to .tsx with allowJs enabled.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens to type annotations when a TypeScript React app is built?

    Types exist only at development time. The compiler checks them, then the bundler erases them, so data arriving at runtime is never verified by your types.
  2. 2. Which type is the best default for a component's children prop?

    ReactNode covers every renderable value: text, numbers, elements, arrays, null, undefined and booleans. JSX.Element would reject plain text and null.
  3. 3. How does imageUrl: string | null differ from imageUrl?: string?

    | null is a value you must supply explicitly. ? means the prop may be omitted (its value is then undefined). The Greeting demo showed that defaults apply to undefined but not to null.
  4. 4. In a click handler on a <button> containing a <span>, which is always the button?

    currentTarget is the element the handler is attached to. target is the innermost element actually clicked, such as the span or an em inside it.
  5. 5. Why use a discriminated union such as { kind: 'link'; href: string } | { kind: 'button'; onPress: () => void }?

    Checking the shared discriminant field tells TypeScript which variant you have, so only that variant's props are available, and invalid combinations are compile errors.

Summary

  • TypeScript checks your React code before it runs: wrong props, missing props and wrong event handlers show up in the editor and in tsc --noEmit.
  • Types are erased at build time, so validate data from the outside world; the bundler does not type-check, so run tsc in CI.
  • Type props as objects: ? for optional, | null for values that may be null, function types for callbacks, and literal unions for variants.
  • Use ReactNode for children, import type for type-only imports, and skip React.FC.
  • Type events with the element they are attached to (ChangeEvent<HTMLInputElement>); use currentTarget for the element with the handler and target for the one clicked.
  • Use discriminated unions for props that depend on each other.
  • Prefer unknown to any and checks to casts.

Next: Typing State, Refs, Context and Reducers