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.
Theory in plain words
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
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} />;
}npm create vite@latest my-app -- --template react-tsany. 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?
Typed React components.
2. What happens to types at build time?
The browser gets plain JS.
3. Safer than any for untrusted data?
unknown forces a check.
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.