Skip to content
FrontDepth, Home

TypeScript

Typing React components

How to type React components with React 19's types: props, children and defaults, event handlers, useState, useRef and useReducer, wrappers around native elements that take ref as a prop, generic components, and props that only make sense in certain combinations.

JuniorMiddleSeniorUpdated 16 November 2026

Reading level

Shows sections up to the selected level.

This topic starts at Junior level.

JuniorConcept

Typing props and children

A component's props are one object, so you type them like any object: a type alias or an interface, and an annotation on the parameter. From then on TypeScript checks every place the component is used. JSX attributes are checked like the properties of an object literal, so a missing, misspelled or wrongly typed prop is a compile error.

TSX
type BadgeProps = {
  label: string;
  tone?: "neutral" | "success" | "danger";
  count?: number;
};

function Badge({ label, tone = "neutral", count }: BadgeProps) {
  return (
    <span className={`badge badge-${tone}`}>
      {label}
      {count !== undefined && <b>{count}</b>}
    </span>
  );
}

<Badge label="New" />;
// Error: property 'label' is missing
<Badge />;
// Error: "warn" is not one of the tones
<Badge label="New" tone="warn" />;
// Error: 'colour' does not exist in BadgeProps
<Badge label="New" colour="red" />;

A ? makes a prop optional. Inside the component its type then includes undefined (count is number | undefined), so TypeScript makes you handle the missing case. A default value in the destructuring removes undefined: tone above is just the union. React 19 removed defaultProps for function components, so destructuring defaults are the way to set them. A default applies only when the value is undefined; a prop passed as null stays null.

type or interface both work for props; pick one convention for the codebase. You rarely write the return type: TypeScript it. React.FC<Props> is optional too. It types the function, but since the React 18 types it does not add children to the props.

children

children is an ordinary prop, and you list it yourself. Its usual type is ReactNode: everything React can render, such as elements, strings, numbers, booleans, null, undefined and arrays of these.

TSX
import type { ReactNode } from "react";

type CardProps = {
  title: string;
  children: ReactNode;
};

function Card({ title, children }: CardProps) {
  return (
    <section>
      <h2>{title}</h2>
      {children}
    </section>
  );
}

ReactElement is narrower: JSX elements only, so <Card>Text</Card> would fail with it. Neither can say "only <li> elements": react.dev notes that TypeScript cannot describe children as a certain type of JSX element. PropsWithChildren<P> adds an optional children?: ReactNode to P, and a style prop takes React.CSSProperties.

JuniorConcept

Typing event handlers

Write a handler inline and you don't type the event at all: TypeScript knows the type of onChange on an <input> and gives it to the parameter.

TSX
function TaskTitle() {
  const [title, setTitle] = useState("");
  // e is React.ChangeEvent<HTMLInputElement>
  return <input value={title} onChange={(e) => setTitle(e.target.value)} />;
}

Move the handler into a named function and that context is gone. Under strict an untyped parameter is an implicit any error, so you annotate it. react.dev's tip: hover over the prop (onChange) in the editor to see which event type it expects.

TSX
function handleChange(event: React.ChangeEvent<HTMLInputElement>) {
  console.log(event.target.value);
}

// or type the whole function with a handler type
const handleKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (event) => {
  if (event.key === "Escape") event.currentTarget.blur();
};

The everyday ones are ChangeEvent (inputs, selects, textareas), MouseEvent, KeyboardEvent and FocusEvent. For onSubmit the current types use SubmitEvent<HTMLFormElement>; the older FormEvent still compiles but is marked deprecated. The type parameter is the element the handler is attached to. These are React's types: import them from react or write React.MouseEvent. A bare MouseEvent is the DOM's own type, and a handler typed with it does not fit onClick.

target or currentTarget

currentTarget is the element the handler is attached to, and it is typed as that element. target is where the event started, possibly a child, so for a click it is typed only as EventTarget:

TSX
function handleClick(event: React.MouseEvent<HTMLButtonElement>) {
  // Error: 'disabled' does not exist on type 'EventTarget'
  event.target.disabled = true;
  event.currentTarget.disabled = true;
}

Change events are the exception: their target is typed as the form element, so e.target.value works in onChange. Elsewhere use currentTarget instead of a cast like event.target as HTMLButtonElement.

Callback props

A component's own event props should pass values, not DOM events. The parent of an AddTaskForm wants a title:

TSX
type AddTaskFormProps = {
  onAdd: (title: string) => void;
};

function AddTaskForm({ onAdd }: AddTaskFormProps) {
  const [title, setTitle] = useState("");

  function handleSubmit(event: React.SubmitEvent<HTMLFormElement>) {
    event.preventDefault();
    onAdd(title.trim());
    setTitle("");
  }

  return (
    <form onSubmit={handleSubmit}>
      <input value={title} onChange={(e) => setTitle(e.target.value)} />
      <button type="submit">Add</button>
    </form>
  );
}
JuniorConcept

useState: inference, unions and null

useState takes its type from the initial value: useState(0) holds a number, useState("") a string, useState(false) a boolean. That is enough when the initial value already shows what the state can hold. Three common cases where it does not:

TSX
const [user, setUser] = useState(null);
// Error: 'User' is not assignable to 'SetStateAction<null>'
setUser(currentUser);

const [tags, setTags] = useState([]);
// Error: 'string' is not assignable to 'never'
setTags(["sale"]);

const [status, setStatus] = useState("idle");
// No error: status is any string, typo included
setStatus("svaed");

Pass the type as a type argument:

TSX
const [user, setUser] = useState<User | null>(null);
const [tags, setTags] = useState<string[]>([]);
const [status, setStatus] = useState<"idle" | "saving" | "saved">("idle");

With User | null, TypeScript makes you check before use: user?.name, or an early if (!user) return <SignInLink />. That is at work. A type argument without an initial value, useState<User>(), gives User | undefined.

Don't lie to skip the check: useState<User>({} as User) compiles, but user.name is undefined until the data arrives, and the type no longer warns you.

Model states, not flags

Separate booleans let a component be in states that make no sense: isLoading while error is set, or data together with an error. A keeps exactly one state at a time and tells TypeScript which fields exist in each:

TSX
type ProfileState =
  | { status: "loading" }
  | { status: "error"; message: string }
  | { status: "ready"; user: User };

function Profile() {
  const [state, setState] = useState<ProfileState>({ status: "loading" });

  if (state.status === "loading") return <p>Loading...</p>;
  if (state.status === "error") return <p role="alert">{state.message}</p>;
  return <h1>{state.user.name}</h1>;
}

After each check TypeScript narrows state: state.message exists only in the error branch, state.user only in the last one. Updates are checked too: setState({ status: "ready" }) without a user does not compile, so the component can't reach "ready" with nothing to show.

JuniorConcept

useRef: DOM nodes and mutable values

useRef has two jobs, and the type follows from the job.

A DOM node. Start with null and name the element type. React sets current to the node after the commit and back to null when the element is removed, so the type is HTMLInputElement | null and TypeScript makes you check it:

TSX
function TaskFilter() {
  const inputRef = useRef<HTMLInputElement>(null);

  function focusInput() {
    // Error: 'inputRef.current' is possibly 'null'
    inputRef.current.focus();
    inputRef.current?.focus();
  }

  return (
    <>
      <input ref={inputRef} />
      <button onClick={focusInput}>Filter</button>
    </>
  );
}

The element type must match where the ref goes: a useRef<HTMLDivElement>(null) passed to <input ref={...}> is a type error.

A mutable value that survives re-renders without causing one, such as a timer id. Its type comes from the initial value or from a type argument:

TSX
function CopyButton({ text }: { text: string }) {
  const [copied, setCopied] = useState(false);
  const hideTimer = useRef<number | null>(null);

  async function copy() {
    await navigator.clipboard.writeText(text);
    setCopied(true);
    if (hideTimer.current !== null) window.clearTimeout(hideTimer.current);
    hideTimer.current = window.setTimeout(() => setCopied(false), 2000);
  }

  return <button onClick={copy}>{copied ? "Copied" : "Copy"}</button>;
}

window.setTimeout returns a number. With @types/node loaded, a bare setTimeout returns Node's Timeout object instead, which is why shared code often writes ReturnType<typeof setTimeout>. Changing current never re-renders: if the screen must show the value, it belongs in state.

What React 19's types changed

  • useRef requires an argument. useRef<HTMLDivElement>() is an error ("Expected 1 argument"); write useRef<HTMLDivElement>(null), or useRef<number>(undefined) for a value that starts empty.
  • There is one RefObject<T>, and current is always writable. In older types useRef<number>(null) gave a read-only ref; MutableRefObject is now deprecated.
  • A ref callback may return a cleanup function, and nothing else. ref={(node) => (instance = node)} returns the node, so it no longer compiles; give the arrow a block body: ref={(node) => { instance = node; }}.
MiddleConcept

useReducer with action unions, and typed context

When several pieces of state change together, useReducer moves the transitions into one function. Type the actions as a : every action has a literal type and only the fields it needs.

TSX
type Line = { id: string; qty: number };
type CartAction =
  | { type: "added"; id: string }
  | { type: "removed"; id: string }
  | { type: "cleared" };

function cartReducer(lines: Line[], action: CartAction): Line[] {
  switch (action.type) {
    case "added":
      return lines.some((l) => l.id === action.id)
        ? lines.map((l) => (l.id === action.id ? { ...l, qty: l.qty + 1 } : l))
        : [...lines, { id: action.id, qty: 1 }];
    case "removed":
      return lines.filter((l) => l.id !== action.id);
    case "cleared":
      return [];
    default: {
      const unhandled: never = action;
      throw new Error(`Unknown action: ${JSON.stringify(unhandled)}`);
    }
  }
}

function Cart() {
  const [lines, dispatch] = useReducer(cartReducer, []);
  return <button onClick={() => dispatch({ type: "cleared" })}>Clear ({lines.length})</button>;
}

Inside each case TypeScript narrows action: action.id exists in "added" and "removed", not in "cleared". dispatch is checked as well: dispatch({ type: "removed" }) without an id is an error, and so is a misspelled type. The never assignment is the exhaustiveness check: add a fourth action and forget its case, and that line stops compiling. The throw still matters: an action rebuilt from JSON.parse is whatever the data says.

React 19's types infer state and action types from the reducer, and react.dev's upgrade guide recommends not passing type arguments to useReducer: annotate the reducer's parameters instead. If you must, the form is now useReducer<State, [Action]>; the old useReducer<React.Reducer<State, Action>> no longer compiles.

Typed context

createContext takes its type from the default value. When there is no sensible default, such as the signed-in session, put null in the type and wrap useContext in a hook that throws, so consumers get a value that is never null:

TSX
type Session = { user: User; signOut: () => void };

const SessionContext = createContext<Session | null>(null);

export function useSession(): Session {
  const session = useContext(SessionContext);
  if (session === null) throw new Error("useSession must be used inside <SessionProvider>");
  return session;
}

export function SessionProvider({ session, children }: { session: Session; children: ReactNode }) {
  return <SessionContext value={session}>{children}</SessionContext>;
}

In React 19 the context itself renders as the provider. A component outside the provider fails at once with a clear message.

MiddleFramework

Wrapping native elements: ComponentProps and ref as a prop

A design-system Button should accept everything a <button> accepts (type, disabled, aria-*, onClick...) without listing it by hand. ComponentProps<"button"> is that list, taken from React's JSX types.

TSX
import type { ComponentProps } from "react";

type ButtonProps = ComponentProps<"button"> & {
  variant?: "primary" | "ghost";
};

export function Button({ variant = "primary", className, ...rest }: ButtonProps) {
  return <button {...rest} className={`btn btn-${variant} ${className ?? ""}`} />;
}

Destructure the props you use and spread the rest onto the element; children, handlers and attributes pass through, checked at the call site (<Button type="sumbit"> is an error). Order matters at run time: attributes after {...rest} override the caller's, attributes before it are defaults the caller can replace, even with an explicit undefined.

ref is a prop in React 19

A function component now receives ref like any other prop, and ComponentProps<"button"> includes it, so the spread above already passes a caller's ref to the <button>. react.dev: forwardRef is no longer necessary and will be deprecated in a future release. When the ref belongs to an inner element, declare it yourself:

TSX
type TextFieldProps = Omit<ComponentProps<"input">, "ref"> & {
  label: string;
  ref?: Ref<HTMLInputElement>;
};

function TextField({ label, id, ref, ...rest }: TextFieldProps) {
  const generatedId = React.useId();
  const inputId = id ?? generatedId;
  return (
    <div className="field">
      <label htmlFor={inputId}>{label}</label>
      <input id={inputId} ref={ref} {...rest} />
    </div>
  );
}

Which helper to use:

  • ComponentProps<"input"> (for elements, the same as ComponentPropsWithRef) includes ref. Use it when the rest props, ref included, land on that element.
  • ComponentPropsWithoutRef<"input"> has no ref. Use it when the component does not put the ref on that element, so a caller cannot pass a ref that silently goes nowhere.
  • ComponentProps<typeof DatePicker> gives the props of an existing component, handy when a library does not export its props type.

Changing a native prop: Omit first

To give a native prop another type, remove it before adding yours. A plain intersection keeps both, and onChange would have to be a React change handler and (value: string) => void at once:

TSX
type SelectProps = Omit<ComponentProps<"select">, "value" | "onChange"> & {
  value: string;
  onChange: (value: string) => void;
};

TypeScript does not check JSX attributes whose name is not a valid identifier, so data-testid passes through any component undeclared.

MiddlePitfalls

Escape hatches that hide bugs

Most type errors in React code have a correct fix and a quick escape. The escape compiles, and the bug moves to run time.

A placeholder state that lies.

TSX
function Greeting() {
  const [user, setUser] = useState<User>({} as User);
  // Compiles, then throws: user.name is undefined until the data arrives
  return <p>Hello, {user.name.toUpperCase()}</p>;
}

{} as User (or null!) tells TypeScript the user is already there. Type the state as User | null and render the missing case.

! on a ref. inputRef.current!.focus() claims the node exists. That holds for an element that is always rendered once the component has mounted, not for one behind a condition. inputRef.current?.focus() costs one character.

Casting the event target. (event.target as HTMLInputElement).value in a click handler compiles even when the click started on an icon inside the button. event.currentTarget is typed as the element the handler is attached to.

any for events and props. (e: any) => ... turns off checking for the whole handler, props: any for the whole component. Hover the prop to find the event type instead.

The global JSX namespace. React 19's types no longer declare a global JSX, so a return type JSX.Element fails with "Cannot find namespace 'JSX'". Write React.JSX.Element, or let TypeScript infer the return type. Declarations for custom elements in JSX.IntrinsicElements move into a declare module block for react or the JSX runtime module.

Implicit returns from ref callbacks. ref={(node) => (instance = node)} returns the node, and React 19's types allow only a cleanup function as the return value. Use a block body.

Reading props of an element. ReactElement["props"] is now unknown instead of any, so code that reads children.props.title stops compiling. Pass the data as props instead, or give the element a type argument (ReactElement<{ title: string }>) where you really inspect elements.

@ts-ignore above JSX. It silences every error on the next line, including ones nobody has seen yet. If an escape is unavoidable, @ts-expect-error with a reason at least fails once the error is gone.

SeniorConcept

Generic components

A list, a table or a picker works for any item type, but each use should keep the link between the items and the callbacks: if the items are products, renderItem receives a product. A function component is a function, so a component works exactly like a generic function.

TSX
import type { Key, ReactNode } from "react";

type ListProps<T> = {
  items: readonly T[];
  getKey: (item: T) => Key;
  renderItem: (item: T) => ReactNode;
  emptyText?: string;
};

export function List<T>({ items, getKey, renderItem, emptyText = "Nothing here" }: ListProps<T>) {
  if (items.length === 0) return <p>{emptyText}</p>;
  return (
    <ul>
      {items.map((item) => (
        <li key={getKey(item)}>{renderItem(item)}</li>
      ))}
    </ul>
  );
}

<List items={products} getKey={(p) => p.sku} renderItem={(p) => `${p.title}: ${p.price}`} />;
// Error: property 'name' does not exist on the product type
<List items={products} getKey={(p) => p.sku} renderItem={(p) => p.name} />;

T is inferred from items at the call site, and the callbacks are checked against it. When there is nothing to infer from, such as an empty array literal, pass the type argument in JSX: <List<Product> items={[]} ... />. readonly T[] also accepts as const arrays. Constraints work as in functions: function Table<T extends { id: string }> may use row.id as the key and rejects rows without an id.

Arrow functions in .tsx files

In a .tsx file, <T> in front of an arrow function parses as a JSX tag. Write <T,>, or use a function declaration:

TSX
export const Grid = <T,>({ items }: { items: T[] }) => <div>{items.length}</div>;

Generic components and refs

forwardRef does not keep a type parameter: wrap a generic component in it and T becomes unknown at the call site, which is why older code needed casts around it. With ref as a prop in React 19, the component declares ref?: Ref<HTMLUListElement> like any other prop and stays generic.

When not to

A type parameter has to connect at least two places. If T appears only in items: T[] and nothing hands an item back to the caller, items: unknown[] or a concrete type says the same with less noise. Generic components also produce longer error messages, so keep them for real shared building blocks.

SeniorExample

Props that depend on each other

Some props only make sense together: a button is either a link (href) or an action (onClick); a modal is either controlled (open and onClose) or not (defaultOpen). Optional props for everything allow every mix, including both and neither. A lists the valid combinations instead:

TSX
type ActionProps =
  | { as: "link"; href: string; children: ReactNode }
  | { as: "button"; onClick: () => void; children: ReactNode };

function Action(props: ActionProps) {
  if (props.as === "link") return <a href={props.href}>{props.children}</a>;
  return (
    <button type="button" onClick={props.onClick}>
      {props.children}
    </button>
  );
}

<Action as="link" href="/pricing">Pricing</Action>;
// Error: 'href' does not exist on the button variant
<Action as="button" href="/pricing" onClick={track}>Pricing</Action>;

Narrowing works on props.as. It also works after destructuring in the parameter list, as long as every destructured property exists in all members and the variables are never reassigned (TypeScript 4.6 and later): with { kind: "text"; value: string } | { kind: "number"; value: number }, a check on kind narrows value. A ...rest object is not narrowed, so a component that spreads the rest checks props.as before destructuring.

Unions without a discriminant are not exclusive

TypeScript accepts props that match one member of a union even when they carry props of another member:

TSX
type ModalProps =
  | { open: boolean; onClose: () => void }
  | { defaultOpen: boolean };
declare function Modal(props: ModalProps): ReactNode;

// Compiles: the first member matches, and defaultOpen comes along
<Modal open onClose={closeModal} defaultOpen />;

Forbid the mix with ?: never for the other member's keys:

TSX
type ModalProps =
  | { open: boolean; onClose: () => void; defaultOpen?: never }
  | { defaultOpen: boolean; open?: never; onClose?: never };

Now the same JSX is an error. The pattern also types a value that depends on a flag: { multiple?: false; value: string } | { multiple: true; value: string[] }.

The cost

Omit<ActionProps, "children"> does not work per member: Omit over a union keeps only the keys common to all members, so href and onClick disappear. Wrapping such a component needs a distributive version, T extends unknown ? Omit<T, K> : never (a that distributes over the union). Error messages grow too. Use unions where an invalid combination would be a real bug, not for every pair of props.

SeniorInterview tips

Interview tips

A 30-second answer. "I type the props as an object type and let TypeScript infer the rest: inline handlers get their event type from the prop, useState from its initial value, useReducer from the reducer. I add types where inference can't know: useState<User | null>(null), useRef<HTMLInputElement>(null), handlers moved out of JSX. Wrappers around native elements take ComponentProps<"button">, and in React 19 they receive ref as a prop. Props that only make sense in certain combinations get a discriminated union, and reusable lists become generic components."

Questions you are likely to get

  • ReactNode, ReactElement or JSX.Element for children? ReactNode for anything renderable, ReactElement for JSX elements only; JSX.Element is the type of a JSX expression (React.JSX.Element in React 19's types).
  • How do you type an onChange handler moved out of JSX? React.ChangeEvent<HTMLInputElement> for the parameter, or React.ChangeEventHandler<HTMLInputElement> for the function. Add target vs currentTarget.
  • What changed in React 19's types? useRef needs an argument and every ref is mutable; ref callbacks return only a cleanup; no global JSX; ReactElement props default to unknown; useReducer infers from the reducer; ref is a prop, so forwardRef is no longer needed.
  • How would you type a Button that takes every native prop? ComponentProps<"button"> plus your own props, Omit for the ones you change, the rest spread onto the element.
  • How do you make two props mutually exclusive? A discriminated union, or ?: never when there is no discriminant.
  • How do you type a generic Select<T>? As a generic function component; mention <T,> in .tsx arrow functions and that forwardRef loses T.

Mistakes that cost points

  • Silencing errors with as, ! or any, especially useState({} as User).
  • Saying React.FC is required, or that it adds children (it hasn't since the React 18 types).
  • Treating types as a run-time check: a prop filled from an API response is only as correct as the response. Types describe the data; they do not verify it.

Senior signal

Talk about trade-offs rather than syntax: inference over annotations, unions only where an invalid combination is a real bug, generic components only for shared building blocks, and wrapper types in a design system that keep native props, refs and accessibility attributes flowing through. Show that you know where the checker stops: at the boundary where data enters the app.

JuniorReview checklist

What to check when reviewing typed React components

Use this list when you review typed React code you did not write: a teammate's pull request, a library's example or an AI assistant's suggestion. A type that lies compiles as well as a correct one, so these bugs surface later, as a crash on data that arrived late or a prop combination nobody handled.

  • Does the type check pass with strict on and no new any, as, ! or @ts-ignore? Run the project's type check (tsc --noEmit): a bundler that only strips types builds code with type errors. Every escape needs a reason; useState({} as User) and ref.current! usually have a typed fix.
  • Does every useState that starts with null, [] or a string literal have a type argument for its real values? useState(null) can only ever hold null, useState([]) is never[], and useState("idle") accepts any string where a union was meant.
  • Are refs typed with the element they are attached to and checked before use? useRef<HTMLInputElement>(null) goes on an <input>, and handlers use ?. or an explicit check; useRef() without an argument does not compile with React 19's types.
  • Are handlers moved out of JSX typed with React's event types, reading currentTarget? React.MouseEvent<HTMLButtonElement>, not the DOM MouseEvent and not any; a cast of event.target hides clicks that start on a child element.
  • Do wrappers of native elements pass the rest props and ref through, with Omit for changed props? Check that ...rest reaches the element, that a component typed with ComponentProps really puts the ref somewhere, and that a changed value or onChange is omitted from the native props first.
  • Can the props express a combination the component does not handle? Write the doubtful call site, such as href with onClick or open with defaultOpen; if it compiles and the component ignores half of it, a discriminated union or ?: never is missing.
  • Does every reducer's switch end in a never check? Add a dummy member to the action union locally: if the reducer still compiles, a new action would be silently ignored.

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    3 predict-output · 4 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    7 questions