React with TypeScript
TypeScript adds static types to JavaScript. In React projects it catches whole classes of bugs before you run anything: a misspelled prop, a missing argument, undefined where a string was expected, a wrong event type. Most new React projects use it — create one with npm create vite@latest my-app -- --template react-ts. Component files then use the .tsx extension.
Note: The
tsxplaygrounds here transpile your code (removing the types) and render it, but don't type-check it. In a real project your editor andtscreport type errors as you type.
Typing props
Describe a component's props with a type (or interface) and annotate the destructured parameter. Optional props get a ?:
type BadgeProps = {
label: string;
count: number;
tone?: 'info' | 'success' | 'danger'; // union of allowed strings
};
const TONES = { info: '#0969da', success: '#1a7f37', danger: '#cf222e' };
function Badge({ label, count, tone = 'info' }: BadgeProps) {
return (
<span style={{ background: TONES[tone], color: 'white', borderRadius: 999, padding: '2px 10px', marginRight: 6 }}>
{label}: {count}
</span>
);
}
export default function App() {
return (
<p>
<Badge label="Open" count={12} />
<Badge label="Merged" count={40} tone="success" />
<Badge label="Failed" count={3} tone="danger" />
{/* <Badge label="Oops" count="3" tone="warning" /> ← two type errors in a real project */}
</p>
);
}The commented line would fail type-checking: count must be a number, and 'warning' isn't one of the allowed tones. Your editor also autocompletes the allowed values.
children and other React types
| Type | Use for |
|---|---|
React.ReactNode |
anything renderable: children, slots |
React.ReactElement |
exactly one JSX element |
React.ComponentProps<'button'> |
all props of a built-in element (for wrappers) |
React.CSSProperties |
a style object |
React.ChangeEvent<HTMLInputElement> |
onChange event of an input |
React.FormEvent<HTMLFormElement> |
onSubmit event |
React.MouseEvent<HTMLButtonElement> |
click events |
import type { ComponentProps, ReactNode, CSSProperties } from 'react';
type CardProps = {
title: string;
footer?: ReactNode;
children: ReactNode;
};
function Card({ title, footer, children }: CardProps) {
const box: CSSProperties = { border: '1px solid #d0d7de', borderRadius: 8, padding: 12, width: 280 };
return (
<section style={box}>
<h3 style={{ marginTop: 0 }}>{title}</h3>
{children}
{footer && <footer style={{ borderTop: '1px solid #eee', marginTop: 8, paddingTop: 8 }}>{footer}</footer>}
</section>
);
}
// Accept every normal <button> prop, plus our own `variant`
type ButtonProps = ComponentProps<'button'> & { variant?: 'primary' | 'ghost' };
function Button({ variant = 'primary', style, ...rest }: ButtonProps) {
const base: CSSProperties =
variant === 'primary'
? { background: '#0969da', color: 'white', border: 'none' }
: { background: 'transparent', border: '1px solid #888' };
return <button {...rest} style={{ ...base, padding: '6px 12px', borderRadius: 6, marginRight: 6, ...style }} />;
}
export default function App() {
return (
<Card title="Delete repository?" footer={<><Button variant="ghost">Cancel</Button><Button onClick={() => console.log('deleted')}>Delete</Button></>}>
<p>This action cannot be undone.</p>
</Card>
);
}Typing state and events
useState infers the type from the initial value. Provide it explicitly when the initial value doesn't tell the whole story — for example null now and an object later:
import { useState } from 'react';
import type { ChangeEvent, FormEvent } from 'react';
type User = { id: number; name: string; email: string };
export default function App() {
const [query, setQuery] = useState(''); // inferred: string
const [user, setUser] = useState<User | null>(null); // explicit union
const [error, setError] = useState<string>(); // string | undefined
function handleChange(e: ChangeEvent<HTMLInputElement>) {
setQuery(e.target.value);
}
function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
if (query.trim().length < 2) {
setError('Please enter at least 2 characters');
setUser(null);
return;
}
setError(undefined);
setUser({ id: 1, name: query.trim(), email: `${query.trim().toLowerCase()}@example.com` });
}
return (
<form onSubmit={handleSubmit}>
<input value={query} onChange={handleChange} placeholder="Name" /> <button>Look up</button>
{error && <p style={{ color: 'crimson' }}>{error}</p>}
{/* TypeScript forces the null check before reading user.name */}
{user && <p>#{user.id} {user.name} <{user.email}></p>}
</form>
);
}Typing reducers with discriminated unions
A union of action types lets TypeScript check every dispatch call and narrow the action inside each case:
import { useReducer } from 'react';
type State = { items: string[]; filter: 'all' | 'short' };
type Action =
| { type: 'add'; item: string }
| { type: 'remove'; index: number }
| { type: 'setFilter'; filter: State['filter'] };
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'add':
return { ...state, items: [...state.items, action.item] }; // action.item is known here
case 'remove':
return { ...state, items: state.items.filter((_, i) => i !== action.index) };
case 'setFilter':
return { ...state, filter: action.filter };
}
}
export default function App() {
const [state, dispatch] = useReducer(reducer, { items: ['kiwi', 'banana', 'fig', 'pineapple'], filter: 'all' });
const visible = state.items.filter((it) => state.filter === 'all' || it.length <= 4);
return (
<div>
<button onClick={() => dispatch({ type: 'add', item: `fruit${state.items.length + 1}` })}>Add</button>{' '}
<button onClick={() => dispatch({ type: 'setFilter', filter: state.filter === 'all' ? 'short' : 'all' })}>
Filter: {state.filter}
</button>
<ul>
{visible.map((it) => (
<li key={it}>{it} <button onClick={() => dispatch({ type: 'remove', index: state.items.indexOf(it) })}>✕</button></li>
))}
</ul>
{/* dispatch({ type: 'add' }) would be an error: property 'item' is missing */}
</div>
);
}Generic components
Components can be generic, just like functions. This list works for any item type and keeps renderItem correctly typed:
import type { ReactNode } from 'react';
type ListProps<T> = {
items: T[];
getKey: (item: T) => string | number;
renderItem: (item: T) => ReactNode;
};
function List<T>({ items, getKey, renderItem }: ListProps<T>) {
return <ul>{items.map((item) => <li key={getKey(item)}>{renderItem(item)}</li>)}</ul>;
}
type Planet = { name: string; moons: number };
const planets: Planet[] = [
{ name: 'Earth', moons: 1 },
{ name: 'Mars', moons: 2 },
{ name: 'Jupiter', moons: 95 },
];
export default function App() {
return (
<List
items={planets}
getKey={(p) => p.name}
renderItem={(p) => <span>🪐 {p.name} — {p.moons} moon{p.moons === 1 ? '' : 's'}</span>}
/>
);
}Inside renderItem, p is automatically a Planet; typing p.moon would be an error.
Typing refs and context
const inputRef = useRef<HTMLInputElement>(null); // DOM ref
const timerRef = useRef<number | null>(null); // mutable value
type Theme = 'light' | 'dark';
const ThemeContext = createContext<Theme>('light');Tip: Don't annotate everything. Let TypeScript infer local variables and
useStatewith obvious initial values; add types at the boundaries — props, context, reducer actions and API responses.
Test yourself
How do you mark the prop tone as optional in a props type?
- tone: optional string
- tone?: string
- tone!: string
- optional tone: string
Which type should children usually have?
- string
- JSX.Element[]
- React.ReactNode
- any
Why write useState<User | null>(null)?
- It is faster
- Inferred from
nullalone, the state could never hold a User - useState requires a generic
- To disable type checking