Every example since Part 3 has been TypeScript, and you've mostly been able to ignore the types. That's on purpose: in React code, good types are mostly inferred and stay out of the way. But a handful of places need you to write them, and those are exactly the places interviewers probe: how to type children, events, refs, a generic component, a reducer's actions, a context that might be missing.
This chapter goes through each one, with the reasoning behind the type, and shows the errors TypeScript gives you when you get it wrong. One thing to keep in mind throughout: the sandbox, like the bundlers from Starting a React app (esbuild, SWC, Vite's dev server and vite build), strips types without checking them. So runnable examples here show runtime behavior, and type errors are shown as static code with the compiler's message, the way you'd see them in your editor.
The problem: types vanish at runtime#
Here's a component with a typed prop, used wrongly. Run it.
type AvatarProps = { name: string; size: number };
function Avatar({ name, size }: AvatarProps) {
const style = { width: size, height: size, fontSize: size / 2.5 };
return (
<div style={{ ...style, borderRadius: "50%", background: "#f6e3d8", display: "grid", placeItems: "center" }}>
{name[0]}
</div>
);
}
export default function App() {
// @ts-expect-error: the sandbox doesn't check, so we say it out loud.
return <Avatar name="Ada" size="large" />;
}No type error, and nothing stops the render. "large" / 2.5 is NaN; React prints a development warning that NaN is an invalid fontSize, the browser ignores width: large and height: large, and the circle becomes a stretched ellipse. That console warning is a lucky side effect of this particular mistake: most wrong-typed props fail with no message at all. In your editor the same line is red before you save:
<Avatar name="Ada" size="large" />
// error TS2322: Type 'string' is not assignable to type 'number'.That's the deal TypeScript offers: it checks your code against your own descriptions of it, at compile time, and then disappears. It can't check data that arrives at runtime (a fetch response, a URL param, localStorage), which is why the boundaries of your app need runtime validation (Zod, from URL and form state) while the inside can trust the types.
Props and children#
A component's props are one object, so you type that object. type and interface both work; most React codebases use type because it composes with unions and intersections, and the choice rarely matters.
type ButtonProps = {
variant?: "primary" | "ghost"; // optional, a union of literals instead of string
disabled?: boolean;
onClick: () => void;
children: React.ReactNode;
};
function Button({ variant = "primary", disabled = false, onClick, children }: ButtonProps) {
return (
<button className={variant} disabled={disabled} onClick={onClick}>
{children}
</button>
);
}Defaults come from destructuring (variant = "primary"), and TypeScript knows variant is never undefined inside the function. React 19 removed defaultProps for function components, so destructuring is the only way.
The interesting question is what to call children. There are three candidates, and they're not the same:
ReactNodeis anything React can render: elements, strings, numbers,null,undefined, booleans, arrays of nodes, portals, and (since React 19's types) promises, for async Server Components. Use it forchildrenand for "slot" props likeiconorfooter. It's whatPropsWithChildrenuses.ReactElementis only the object JSX creates ({ type, props, key }). Use it when you need to inspect or clone an element, which is rare.JSX.Elementis what a JSX expression's type is: an interface extendingReactElement<any, any>. React 19's types removed the globalJSXnamespace, so writeReact.JSX.Element(or importJSXfromreact). It's fine as a return type annotation, too narrow forchildren.
type CardProps = { title: string; children: React.JSX.Element };
<Card title="Empty">Nothing yet</Card>
// error TS2322: Type 'string' is not assignable to type 'Element'.Change children to React.ReactNode and both a string and an element work.
Events#
Inline handlers need no types at all: TypeScript knows which element the JSX is on, so it infers the event.
<input onChange={(e) => setQuery(e.target.value)} /> // e is ChangeEvent<HTMLInputElement>You only write event types when the handler is a separate function. The names mirror the DOM, prefixed by React's namespace, and the type parameter is the element the handler is attached to:
import type { ChangeEvent, MouseEvent, KeyboardEvent, SubmitEvent } from "react";
function onQueryChange(e: ChangeEvent<HTMLInputElement>) {
setQuery(e.target.value); // target is typed as the input
}
function onRowClick(e: MouseEvent<HTMLTableRowElement>) {
console.log(e.currentTarget.dataset.id); // currentTarget: the element with the handler
}
function onKeyDown(e: KeyboardEvent<HTMLDivElement>) {
if (e.key === "Escape") close();
}
function onSubmit(e: SubmitEvent<HTMLFormElement>) {
e.preventDefault();
const data = new FormData(e.currentTarget);
console.log("submitted by", e.submitter); // React 19.3 added submitter
}Two details worth knowing. currentTarget is the element the handler is attached to and is always typed precisely; target is wherever the event started, which for bubbling events could be any descendant, so its type is looser. And in the current @types/react (19.3), FormEvent is deprecated with a note that it "doesn't actually exist": use SubmitEvent for onSubmit, ChangeEvent for onChange, and InputEvent for onInput. Older code uses FormEvent everywhere; it still compiles.
For props that are callbacks, describe what your component reports, not the DOM event:
type BookRowProps = {
book: Book;
onToggleRead: (id: number) => void; // not (e: MouseEvent) => void
};The parent shouldn't need to know your component is a button inside a table row.
Refs#
Since React 19, useRef requires an argument, and the types have three overloads. The one you use for DOM refs is "pass null, get a ref whose current can be null":
const inputRef = useRef<HTMLInputElement>(null); // RefObject<HTMLInputElement | null>
function focus() {
inputRef.current?.focus(); // must handle null: before mount, after unmount
}
return <input ref={inputRef} />;For a mutable value that isn't a DOM node (a timer id, the previous value), type it directly:
const timer = useRef<number | null>(null);
timer.current = window.setTimeout(tick, 1000);React 19's types made RefObject.current writable and deprecated MutableRefObject, so there's one ref type instead of two that differed only in readonly-ness.
Ref as a prop. In React 19 a function component receives ref as a regular prop, so forwardRef is no longer needed. The cleanest way to type it is to take the element's own props, which include ref:
import type { ComponentProps } from "react";
function TextInput({ label, ref, ...rest }: ComponentProps<"input"> & { label: string }) {
return (
<label>
{label} <input ref={ref} {...rest} />
</label>
);
}
// The parent's ref reaches the <input>:
const ref = useRef<HTMLInputElement>(null);
<TextInput label="Title" ref={ref} placeholder="Dune" />;forwardRef still works in 19 and you'll see it in every library written before it, but new code passes ref like any other prop.
Reusing the DOM's props: ComponentProps#
A wrapper around a native element should accept everything the element accepts: type, disabled, aria-*, data-*, every event. Don't list them by hand; derive them.
import type { ComponentProps, ComponentPropsWithoutRef } from "react";
type ButtonProps = ComponentProps<"button"> & { variant?: "primary" | "ghost" };
function Button({ variant = "primary", className, ...rest }: ButtonProps) {
return <button className={`btn btn-${variant} ${className ?? ""}`} {...rest} />;
}ComponentProps<"button">is the props of the intrinsic<button>, includingrefin React 19.ComponentPropsWithoutRef<"button">is the same minusref. Use it when you don't want to expose the ref, or when you combine props from several sources.ComponentProps<typeof SomeComponent>gets the props of any component, which is handy for wrapping a third-party component whose props type isn't exported.- Use
Omitto replace a native prop with your own meaning:Omit<ComponentProps<"input">, "onChange"> & { onChange: (value: string) => void }.
State: inference, unions and impossible states#
useState infers from the initial value, which is usually what you want: useState(0) is a number, useState("") a string. You need an explicit type when the initial value doesn't show every shape the state can take.
const [user, setUser] = useState<User | null>(null); // starts empty, filled later
const [tags, setTags] = useState<string[]>([]); // [] alone infers never[]
setTags(["craft"]);
// without <string[]>: error TS2322: Type 'string' is not assignable to type 'never'.The bigger design question is how to model state that has several phases. The common first version uses one variable per concern:
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [books, setBooks] = useState<Book[] | null>(null);Three variables allow eight combinations, and only four make sense. Nothing stops "loading, with an error, with stale data". A discriminated union describes exactly the valid ones, with a literal status field that TypeScript uses to narrow:
type BooksState =
| { status: "idle" }
| { status: "loading" }
| { status: "error"; message: string }
| { status: "success"; books: Book[] };
function view(state: BooksState) {
switch (state.status) {
case "loading":
return "Loading…";
case "error":
return state.message; // narrowed: message exists here
case "success":
return `${state.books.length} books`; // and books exists here
case "idle":
return "";
}
}Accessing state.books outside the "success" branch is a compile error, so you can't render data that isn't there. This is the same "make impossible states impossible" idea as State machines, expressed in types.
This component tracks a request with three separate pieces of state. Click Load (fails), then Load: the error stays on screen next to the data. Click Load (fails) again: the old books stay next to the new error. Replace the three variables with one discriminated union so only one phase can show at a time.
import { useState } from "react";
import { fakeFetch } from "guide-tools";
type Book = { id: number; title: string };
export default function App() {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [books, setBooks] = useState<Book[] | null>(null);
async function load(fail: boolean) {
setIsLoading(true);
try {
setBooks(await fakeFetch("/books", { fail, delay: 150 }));
} catch (e) {
setError((e as Error).message);
} finally {
setIsLoading(false);
}
}
return (
<div>
<button onClick={() => load(false)}>Load</button>{" "}
<button onClick={() => load(true)}>Load (fails)</button>
{isLoading && <p>Loading…</p>}
{error && <p role="alert">Error: {error}</p>}
{books && <p>{books.length} books loaded</p>}
</div>
);
}useReducer with typed actions#
The same idea applies to actions. Type actions as a discriminated union on type, and the reducer's switch narrows each case's payload. Add a never check in the default branch, and forgetting to handle a new action becomes a compile error.
import { useReducer, useState } from "react";
import { books as fixture } from "guide-tools";
type Book = { id: number; title: string; read: boolean };
type Action =
| { type: "added"; title: string }
| { type: "toggled"; id: number }
| { type: "removed"; id: number };
let nextId = 100;
function booksReducer(books: Book[], action: Action): Book[] {
switch (action.type) {
case "added":
return [...books, { id: nextId++, title: action.title, read: false }];
case "toggled":
return books.map((b) => (b.id === action.id ? { ...b, read: !b.read } : b));
case "removed":
return books.filter((b) => b.id !== action.id);
default: {
// If a new action type is added and not handled, this line stops compiling.
const unhandled: never = action;
throw new Error(`Unhandled action: ${JSON.stringify(unhandled)}`);
}
}
}
const initial: Book[] = fixture.slice(0, 3).map((b) => ({ id: b.id, title: b.title, read: false }));
export default function App() {
const [books, dispatch] = useReducer(booksReducer, initial);
const [title, setTitle] = useState("");
return (
<div>
<form
onSubmit={(e) => {
e.preventDefault();
if (title.trim()) dispatch({ type: "added", title: title.trim() });
setTitle("");
}}
>
<input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Add a book" />
</form>
<ul>
{books.map((b) => (
<li key={b.id}>
<label>
<input type="checkbox" checked={b.read} onChange={() => dispatch({ type: "toggled", id: b.id })} />{" "}
{b.title}
</label>{" "}
<button onClick={() => dispatch({ type: "removed", id: b.id })}>×</button>
</li>
))}
</ul>
</div>
);
}What the types buy you, shown as the errors you'd get:
dispatch({ type: "toggled" });
// error TS2345: Argument of type '{ type: "toggled"; }' is not assignable to parameter of type 'Action'.
// Property 'id' is missing in type '{ type: "toggled"; }' but required in type '{ type: "toggled"; id: number; }'.
// After adding | { type: "renamed"; id: number; title: string } to Action:
const unhandled: never = action;
// error TS2322: Type '{ type: "renamed"; id: number; title: string; }' is not assignable to type 'never'.useReducer infers the state and action types from the reducer's signature, so the component code has no annotations at all. The types live in one place.
Generic components#
A list, a table, a select or a combobox works the same whatever the item type is. Typing its items as any loses the connection between what you pass in and what your callbacks receive. A generic component keeps it: the type parameter is inferred from the items you pass, and flows into getKey and renderItem.
import type { ReactNode } from "react";
import { books, users } from "guide-tools";
type ListProps<T> = {
items: T[];
getKey: (item: T) => string | number;
renderItem: (item: T) => ReactNode;
empty?: ReactNode;
};
function List<T>({ items, getKey, renderItem, empty = <p>Nothing here.</p> }: ListProps<T>) {
if (items.length === 0) return <>{empty}</>;
return (
<ul>
{items.map((item) => (
<li key={getKey(item)}>{renderItem(item)}</li>
))}
</ul>
);
}
export default function App() {
return (
<>
<h4>Books</h4>
{/* T is inferred as the book type, so b.year type-checks */}
<List items={books.slice(0, 3)} getKey={(b) => b.id} renderItem={(b) => `${b.title} (${b.year})`} />
<h4>Users</h4>
<List items={users} getKey={(u) => u.id} renderItem={(u) => `${u.name}, ${u.role}`} />
<h4>Nothing</h4>
<List items={[] as string[]} getKey={(s) => s} renderItem={(s) => s} empty={<p>No tags yet.</p>} />
</>
);
}The payoff is in the editor: in renderItem={(b) => b.titel}, TypeScript knows b is a book and flags the typo:
<List items={books} getKey={(b) => b.id} renderItem={(b) => b.titel} />
// error TS2551: Property 'titel' does not exist on type '{ id: number; title: string; ... }'.
// Did you mean 'title'?One syntax trap: in a .tsx file, an arrow function's type parameter <T> looks like a JSX tag. Write const List = <T,>(props: ListProps<T>) => ... (the trailing comma disambiguates) or use a function declaration, as above.
Implement Picker<T>: it renders one button per item, labelled with getLabel(item), keyed by getKey(item), and calls onPick(item) with the original item when clicked. The app already uses it for books and users; it should work for both without any casts.
type PickerProps<T> = {
items: T[];
getKey: (item: T) => string | number;
getLabel: (item: T) => string;
onPick: (item: T) => void;
};
export function Picker<T>(props: PickerProps<T>) {
// TODO: one <button> per item that calls onPick with that item
return null;
}Polymorphic components#
Design systems often want one component that can render as different elements: a Text that's a span by default but sometimes a label or an a, with the right props for each. That's a polymorphic component, typed with a generic over ElementType:
import type { ComponentPropsWithoutRef, ElementType, ReactNode } from "react";
type TextProps<C extends ElementType> = {
as?: C;
children: ReactNode;
} & Omit<ComponentPropsWithoutRef<C>, "as" | "children">;
export function Text<C extends ElementType = "span">({ as, children, ...rest }: TextProps<C>) {
const Component = as ?? "span";
return <Component {...rest}>{children}</Component>;
}<Text as="a" href="/books">Books</Text> // OK: href is an <a> prop
<Text as="label" htmlFor="title">Title</Text> // OK
<Text as="button" href="/books">Books</Text>
// error TS2322: Type '{ children: string; as: "button"; href: string; }' is not assignable to
// type 'IntrinsicAttributes & TextProps<"button">'.
// Property 'href' does not exist on type 'IntrinsicAttributes & TextProps<"button">'. (abridged)It works, but it's the most expensive type in this chapter: slow to check in big unions, confusing errors, and refs need extra care. Many libraries moved to the asChild pattern instead (Radix's Slot): the component renders its single child and merges its props onto it, so <Button asChild><a href="/books">Books</a></Button> gets the anchor's real types for free. Reach for full polymorphism only when a design system genuinely needs it.
satisfies: check without widening#
satisfies (TypeScript 4.9+) checks that a value matches a type but keeps the value's own, narrower type. That's exactly what you want for configuration objects in React apps:
type Route = { path: string; label: string };
const nav = {
home: { path: "/", label: "Home" },
books: { path: "/books", label: "Books" },
} satisfies Record<string, Route>;
nav.books.path; // OK, and the editor knows the keys are "home" | "books"
nav.authors.path;
// error TS2339: Property 'authors' does not exist on type '{ home: {...}; books: {...}; }'.With a type annotation (const nav: Record<string, Route> = ...) the keys widen to string, so nav.authors compiles and crashes at runtime. You've already seen satisfies in the last chapter's React Router config files; it's become the idiomatic way to type config.
Context that can't be missing#
createContext needs a default value, and for most contexts there's no sensible one: a "current user" or "theme setter" outside its provider is a bug. The pattern is to type the context as T | null, default it to null, and expose a hook that throws when the provider is missing. Every consumer then gets a non-null T.
import { createContext, use, useState, type ReactNode } from "react";
type Auth = { user: { name: string } | null; signIn: (name: string) => void; signOut: () => void };
const AuthContext = createContext<Auth | null>(null);
function useAuth(): Auth {
const auth = use(AuthContext);
if (!auth) throw new Error("useAuth must be used inside <AuthProvider>");
return auth; // narrowed to Auth: no null checks in components
}
function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<Auth["user"]>(null);
const value: Auth = { user, signIn: (name) => setUser({ name }), signOut: () => setUser(null) };
return <AuthContext value={value}>{children}</AuthContext>;
}
function Header() {
const { user, signIn, signOut } = useAuth();
return user ? (
<p>
Hi, {user.name} <button onClick={signOut}>Sign out</button>
</p>
) : (
<button onClick={() => signIn("Ada")}>Sign in</button>
);
}
export default function App() {
return (
<>
<AuthProvider>
<Header />
</AuthProvider>
{/* Uncomment to see the error a missing provider gives you: */}
{/* <Header /> */}
</>
);
}The alternative, createContext<Auth>({} as Auth), lies to the compiler: components outside the provider type-check and then crash on undefined is not a function somewhere far from the cause. The throwing hook fails at the exact place, with a message that says what to do. (Memoizing value is the Compiler's job, or useMemo's if you don't use it; see Context.)
Pitfalls#
Check your understanding#
A Card component should accept text, elements, lists of elements, or nothing as its children. What's the right type?
Given type Size = "sm" | "md" and function Badge(props: { size: Size; children: React.ReactNode }) {...}, predict which of these lines are type errors under strict, and why.
const a = <Badge size="sm">New</Badge>;
const s = "md";
const b = <Badge size={s}>New</Badge>;
let t = "md";
const c = <Badge size={t}>New</Badge>;
const d = <Badge size="lg">{null}</Badge>;
const ref = useRef<HTMLDivElement>(null);
ref.current.focus();"How do you type component state that goes through loading, error and success phases? Why not three booleans?"
Interview angle
In React, most types are inferred: inline event handlers, useState with a real initial value, useReducer from the reducer's signature. You write types at the edges. Props get an object type, with ReactNode for children. Separate handlers use ChangeEvent, SubmitEvent and friends. DOM refs are useRef<T>(null), nullable, and in React 19 ref is a plain prop typed through ComponentProps. Multi-phase state and reducer actions are discriminated unions, so impossible states can't be represented. Generic components keep the link between items and callbacks. And remember types are erased: bundlers don't check them, so CI runs tsc and runtime data gets validated.
What's the difference between ReactNode, ReactElement and JSX.Element?
How do you type refs in React 19, including passing a ref to a child?
How would you model loading, error and success state in TypeScript?
When and how do you write a generic component?
How do you type a polymorphic as prop, and is it worth it?
Your Vite app builds and deploys with type errors in it. How is that possible, and what do you change?
Recap#
- Types are erased before code runs. Bundlers strip them without checking (
next buildis the exception), so runtscin CI and validate runtime data at the boundaries. - Use
ReactNodeforchildrenand slots;ReactElementandReact.JSX.Elementare narrower. React 19's types dropped the globalJSXnamespace and deprecatedMutableRefObject, and@types/react19.3 deprecatesFormEventin favor ofSubmitEvent,ChangeEventandInputEvent. - Inline handlers infer their event types. DOM refs are
useRef<T>(null)and nullable. In React 19,refis a regular prop, typed throughComponentProps<"input">. - Model multi-phase state and reducer actions as discriminated unions; add a
nevercheck for exhaustiveness. - Generic components keep the link between
itemsand callbacks;ComponentPropsreuses native props; polymorphicasprops work but are costly;satisfieschecks config without widening; context getsT | nullplus a throwing hook.
Sources#
- react.dev: Using TypeScript, useRef, React 19 upgrade guide: TypeScript changes
@types/react19.3.1 type definitions (index.d.ts)- TypeScript handbook: Narrowing and discriminated unions, Generics, satisfies
- React TypeScript Cheatsheet: Polymorphic components
- Facts checked November 24, 2026.