Home / Learn React / React with TypeScript

React with TypeScript

TypeScript adds types to JavaScript. In React it catches wrong props and bad state early, and gives great autocomplete.

In shortType your props with a type or interface, let TypeScript infer useState, and type events with React types.

Theory in plain words

Types disappear at build timeApp.tsxtsc checks typesVite strips themPlain JavaScriptbundleBrowser runs it
Types disappear at build time

What it is

TypeScript checks your code before it runs. In React you describe the shape of props, state and events, and the editor warns about mistakes.

Why we use it

Many bugs are wrong or missing props, typos in object keys or undefined values. Types find them while you type.

How it works

Files use .tsx. You write type Props = {...}, and TypeScript infers most other things. A build tool removes the types, so the browser still receives plain JavaScript.

Where it is used

  • Teams, long lived projects, shared component libraries
Props, state and events
import { useState, type ReactNode, type ChangeEvent } from "react";

type ButtonProps = { label: string; onClick?: () => void; children?: ReactNode };
function Button({ label, onClick }: ButtonProps) { return <button onClick={onClick}>{label}</button>; }

type User = { id: number; name: string };
function Users() {
  const [users, setUsers] = useState<User[]>([]);          // explicit when the start value is empty
  const [q, setQ] = useState("");                           // inferred as string
  const onChange = (e: ChangeEvent<HTMLInputElement>) => setQ(e.target.value);
  return <input value={q} onChange={onChange} />;
}
Start a Vite + React + TypeScript app
npm create vite@latest my-app -- --template react-ts
Tip:Avoid any. Use unknown for data you do not trust yet, then narrow it with checks or a schema library such as Zod.

Quick quiz

1. What do .tsx files contain?

2. What happens to types at build time?

3. Safer than any for untrusted data?

Common questions

What do .tsx files contain?

TypeScript with JSX. Typed React components.

What happens to types at build time?

Removed. The browser gets plain JS.

Safer than any for untrusted data?

unknown. unknown forces a check.