React with TypeScript
Overview
TypeScript adds static types to JavaScript, and it’s now the default for most professional React projects. Types catch mistakes before you run the code — a misspelled prop, a missing argument, a possibly-null value — and they make editors far more helpful with autocomplete and inline documentation. This lesson covers the patterns you need for typing React code.
Setting up
npm create vite@latest course-catalog -- --template react-tsThe template gives you .tsx files, a tsconfig.json and a build script of tsc -b && vite build: TypeScript checks types, then Vite builds. (Vite itself strips types without checking them, so the dev server stays fast — rely on your editor and tsc for errors.)
The template uses TypeScript 7, the native, much faster rewrite of the compiler, where strict mode is on by default — so implicit anys and unchecked nulls are errors. Keep it that way.
Typing props
Describe the props with a type, then annotate the destructured parameter:
type CourseCardProps = {
title: string;
lessons: number;
level?: 'beginner' | 'intermediate' | 'advanced'; // optional, and only these strings
isNew?: boolean;
};
export function CourseCard({ title, lessons, level = 'beginner', isNew = false }: CourseCardProps) {
return (
<article>
<h2>{title} {isNew && <span className="badge">New</span>}</h2>
<p>{lessons} lessons · {level}</p>
</article>
);
}Now <CourseCard title="React" /> is an error (lessons is missing), and level="expert" is an error too. Union types of string literals are a lightweight way to model variants.
type and interface both work for props; many React codebases use type for consistency, since it can also express unions.
Children and other React types
| Type | Use for |
|---|---|
ReactNode |
anything React can render: elements, strings, numbers, arrays, null — use for children and slot props |
ReactElement |
specifically a JSX element |
CSSProperties |
a style object |
ComponentProps<'button'> |
all the props a <button> accepts |
ComponentProps<typeof CourseCard> |
the props of one of your components |
import type { ReactNode } from 'react';
type PanelProps = {
title: string;
actions?: ReactNode;
children: ReactNode;
};Function props
type CourseListProps = {
courses: Course[];
onSelect: (id: number) => void;
};Extending HTML elements
A Button that accepts everything a <button> does, plus a variant:
import type { ComponentProps } from 'react';
type ButtonProps = ComponentProps<'button'> & {
variant?: 'primary' | 'secondary';
};
export function Button({ variant = 'primary', className, ...props }: ButtonProps) {
return <button className={`btn btn-${variant} ${className ?? ''}`} {...props} />;
}ComponentProps<'button'> includes onClick, disabled, type, aria-* and — in React 19 — ref, so refs pass straight through.
Typing state
useState infers the type from the initial value:
const [count, setCount] = useState(0); // number
const [query, setQuery] = useState(''); // stringPass a type argument when the initial value doesn’t tell the whole story:
type Status = 'idle' | 'loading' | 'success' | 'error';
const [status, setStatus] = useState<Status>('idle');
const [user, setUser] = useState<User | null>(null);
const [courses, setCourses] = useState<Course[]>([]); // [] alone would be never[]With user typed as User | null, TypeScript forces you to check for null before using it — exactly the bug class it’s best at preventing.
useReducer
Type the state and a discriminated union of actions; TypeScript then narrows action inside each case:
type CartState = { items: CartItem[] };
type CartAction =
| { type: 'added'; course: Course }
| { type: 'removed'; id: number }
| { type: 'cleared' };
function cartReducer(state: CartState, action: CartAction): CartState {
switch (action.type) {
case 'added':
return { items: [...state.items, { ...action.course, qty: 1 }] }; // action.course is known here
case 'removed':
return { items: state.items.filter((i) => i.id !== action.id) }; // action.id is known here
case 'cleared':
return { items: [] };
}
}
const [cart, dispatch] = useReducer(cartReducer, { items: [] });
dispatch({ type: 'removed', id: 7 }); // ✓
dispatch({ type: 'removed' }); // ✗ id is missingTyping events
Inline handlers are inferred from the element — no annotations needed:
<input onChange={(e) => setQuery(e.target.value)} /> // e is ChangeEvent<HTMLInputElement>When you write the handler separately, annotate the event:
import type { ChangeEvent, FormEvent, KeyboardEvent, MouseEvent } from 'react';
function handleChange(e: ChangeEvent<HTMLInputElement>) {
setQuery(e.target.value);
}
function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
const data = new FormData(e.currentTarget);
}
function handleKeyDown(e: KeyboardEvent<HTMLInputElement>) {
if (e.key === 'Escape') setQuery('');
}
function handleClick(e: MouseEvent<HTMLButtonElement>) { … }Tip: hover over onChange on an element in your editor to see the exact type it expects.
Typing refs
Give DOM refs the element type and an initial null:
const inputRef = useRef<HTMLInputElement>(null);
function focus() {
inputRef.current?.focus(); // current is HTMLInputElement | null
}
<input ref={inputRef} />For a ref that stores a value (not a DOM node), type the value: useRef<number | null>(null) for an interval id.
To accept a ref in your own component (React 19’s ref-as-prop), type it with Ref:
import type { Ref } from 'react';
type TextFieldProps = { label: string; ref?: Ref<HTMLInputElement> };
function TextField({ label, ref }: TextFieldProps) {
return <label>{label}<input ref={ref} /></label>;
}Typing context
Create the context with the value’s type, using null for “no provider”:
type AuthContextValue = {
user: User | null;
login: (email: string, password: string) => Promise<void>;
logout: () => void;
};
const AuthContext = createContext<AuthContextValue | null>(null);
export function useAuth() {
const ctx = useContext(AuthContext);
if (!ctx) throw new Error('useAuth must be used inside <AuthProvider>');
return ctx; // narrowed to AuthContextValue
}The throw-if-missing hook from Context becomes even more valuable: after the check, TypeScript knows the value isn’t null, so consumers never need ! or ?..
Typing custom hooks and generic components
Hooks are functions, so annotate parameters and let return types be inferred — or add them for clarity:
export function useLocalStorage<T>(key: string, initialValue: T) {
const [value, setValue] = useState<T>(() => {
const stored = localStorage.getItem(key);
return stored !== null ? (JSON.parse(stored) as T) : initialValue;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue] as const; // a tuple, like useState
}
const [theme, setTheme] = useLocalStorage<'light' | 'dark'>('theme', 'light');Components can be generic too — a list that works for any item type:
type ListProps<T> = {
items: T[];
getKey: (item: T) => string | number;
renderItem: (item: T) => ReactNode;
};
export function List<T>({ items, getKey, renderItem }: ListProps<T>) {
return <ul>{items.map((item) => <li key={getKey(item)}>{renderItem(item)}</li>)}</ul>;
}
<List items={courses} getKey={(c) => c.id} renderItem={(c) => c.title} /> // c is CourseTyping API data
Types disappear at runtime, so res.json() returns any — TypeScript can’t know what the server sent. Either annotate (and trust the API), or validate at the boundary with a schema, which gives you both a runtime check and a type:
import { z } from 'zod';
const CourseSchema = z.object({ id: z.number(), title: z.string(), level: z.enum(['beginner', 'intermediate', 'advanced']) });
type Course = z.infer<typeof CourseSchema>;
async function fetchCourse(id: number): Promise<Course> {
const res = await fetch(`/api/courses/${id}`);
return CourseSchema.parse(await res.json());
}Practical advice
- Don’t annotate what TypeScript can infer — let
useState(0)be a number. - Avoid
any. If you truly don’t know a type, useunknownand narrow it. - Avoid the non-null assertion
!except for things you’ve guaranteed exist (likedocument.getElementById('root')!inmain.tsx). - Export shared types (
Course,User) from one module and import them withimport type.
TypeScript shines in refactoring. Rename a prop or change a data shape, and the compiler lists every place that needs updating — invaluable as an app grows.
Type a course card and a search form
Convert these components to TypeScript. Define a Course type (id: number, title: string, level: 'beginner' | 'intermediate' | 'advanced', optional price). Type CourseCard’s props (including an optional onSelect(id: number) and children), type the SearchForm’s state, change and submit events, and give useRef the right element type so inputRef.current?.focus() compiles. Make sure passing level="expert" is a type error.
import { useRef, useState } from 'react';
export function CourseCard({ course, onSelect, children }) {
return (
<article onClick={() => onSelect?.(course.id)}>
<h2>{course.title}</h2>
{children}
</article>
);
}
export function SearchForm({ onSearch }) {
const [query, setQuery] = useState('');
const inputRef = useRef(null);
function handleSubmit(e) {
e.preventDefault();
onSearch(query);
inputRef.current.focus();
}
return (
<form onSubmit={handleSubmit}>
<input ref={inputRef} value={query} onChange={(e) => setQuery(e.target.value)} />
</form>
);
}import { useRef, useState, type FormEvent, type ReactNode } from 'react';
export type Level = 'beginner' | 'intermediate' | 'advanced';
export type Course = {
id: number;
title: string;
level: Level;
price?: number;
};
type CourseCardProps = {
course: Course;
onSelect?: (id: number) => void;
children?: ReactNode;
};
export function CourseCard({ course, onSelect, children }: CourseCardProps) {
return (
<article onClick={() => onSelect?.(course.id)}>
<h2>{course.title}</h2>
{children}
</article>
);
}
type SearchFormProps = {
onSearch: (query: string) => void;
};
export function SearchForm({ onSearch }: SearchFormProps) {
const [query, setQuery] = useState(''); // inferred as string
const inputRef = useRef<HTMLInputElement>(null);
function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
onSearch(query);
inputRef.current?.focus();
}
return (
<form onSubmit={handleSubmit}>
<input ref={inputRef} value={query} onChange={(e) => setQuery(e.target.value)} />
</form>
);
}
// <CourseCard course={{ id: 1, title: 'React', level: 'expert' }} />
// ✗ Type '"expert"' is not assignable to type 'Level'.Summary
- Create a typed project with
npm create vite@latest my-app -- --template react-ts; files use the.tsxextension. - Type props with a
typeorinterfaceand annotate the destructured parameter; useReactNodefor children. useStateinfers simple types; pass a type argument for unions,nullstarts and empty arrays.- Event handlers inline are inferred; standalone ones use types like
ChangeEvent<HTMLInputElement>. - Type DOM refs with
useRef<HTMLInputElement>(null)and context values withcreateContext<T | null>(null).