Sub topic 3
Modeling Advanced React Components with TypeScript
Assume you know function components, JSX, hooks, unions, and generics. These patterns help the compiler check component boundaries and state transitions.
Modeling variants with discriminated unions
A discriminated union is a union whose members share a property with different literal values. TypeScript uses that property to narrow the remaining fields.
type ActionButtonProps =
| { kind: "link"; href: string; label: string }
| { kind: "action"; onClick: () => void; label: string };
export function ActionButton(props: ActionButtonProps) {
if (props.kind === "link") {
return <a href={props.href}>{props.label}</a>;
}
return <button onClick={props.onClick}>{props.label}</button>;
}A link cannot accidentally receive onClick, and an action cannot accidentally receive href.
Typing `useReducer` with action unions
Use the same idea for reducer actions. Each action’s type identifies its fields.
type State = { count: number };
type Action =
| { type: "increment" }
| { type: "set"; value: number };
function reducer(state: State, action: Action): State {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "set":
return { count: action.value };
}
}With strict checking, dispatching an unknown action or omitting value produces an error.
Typing custom hooks and tuple returns
When a hook returns a tuple, as const preserves each position’s type.
import { useState } from "react";
export function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = () => setOn(value => !value);
return [on, toggle] as const;
}Without as const, TypeScript may infer an array whose elements share a broad union type.
Typing context and its provider
Use null as the context default, then hide the check inside a custom hook.
import { createContext, useContext, useState, type ReactNode } from "react";
type Theme = "light" | "dark";
type ThemeValue = { theme: Theme; setTheme: (theme: Theme) => void };
const ThemeContext = createContext<ThemeValue | null>(null);
export function useTheme() {
const value = useContext(ThemeContext);
if (!value) throw new Error("useTheme requires ThemeProvider");
return value;
}
export function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState<Theme>("light");
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}Generic components
A generic component works with many item types while preserving type safety.
function List<T>({ items, renderItem }: {
items: T[];
renderItem: (item: T) => React.ReactNode;
}) {
return <ul>{items.map((item, i) => <li key={i}>{renderItem(item)}</li>)}</ul>;
}Forwarding refs
forwardRef takes the ref element type first and the props type second.
import { forwardRef, type ComponentPropsWithoutRef } from "react";
export const TextInput = forwardRef<
HTMLInputElement,
ComponentPropsWithoutRef<"input">
>((props, ref) => <input ref={ref} {...props} />);Exercise
Why does ActionButton narrow correctly after checking props.kind?
Show answer
kind is a discriminant, so each literal value identifies one union member and its available properties.