Design generic component contracts
Preserve the relationship between data and callbacks
A generic component accepts a type parameter instead of hard-coding one data shape. The same parameter can connect a list of records to a callback that receives one of those records. Unlike any, a generic preserves information about the caller’s type. This chapter assumes TypeScript unions and typed props from Chapter 29. Use React 19 with matching types and a compatible TypeScript compiler; React Hook Form 7, Zod 4 and compatible resolver 5 are proposed for the forms lane. Exact patches and peer dependencies require verification before installation.
import React,{useState} from 'react';type ListProps<T extends {id:string}>={items:readonly T[]; label:(item:T)=>string; onPick:(item:T)=>void};function PickList<T extends {id:string}>({items,label,onPick}:ListProps<T>){ return <ul>{items.map(item=><li key={item.id}><button onClick={()=>onPick(item)}>{label(item)}</button></li>)}</ul>;}export default function App(){ const [chosen,setChosen]=useState('None'); const items=[{id:'p',name:'Paper',stock:4},{id:'b',name:'Brush',stock:2}]; return <><PickList items={items} label={i=>`${i.name} (${i.stock})`} onPick={i=>setChosen(i.name)}/><p role="status">Selected: {chosen}</p></>;}Two buttons display Paper (4) and Brush (2). Clicking Brush updates Selected to Brush. The compiler infers the full record type from items; label and onPick receive that type. The constraint permits reading id without assuming every T has a name. IDs must be unique among siblings; the type does not enforce uniqueness. Use readonly arrays to communicate that the list should not mutate the input. In TSX, a generic arrow such as <T,>(value:T)=>value needs the comma to disambiguate JSX; a function declaration avoids this issue.
Keep business contracts outside the renderer
export type Row = {id:string; label:string};export function selectRow<T extends {id:string}>(rows:readonly T[], id:string):T|undefined { return rows.find(row=>row.id===id);}export type Draft = {title:string; items:{name:string}[]; delivery:'pickup'|'desk'};export type Result = {kind:'saved'; count:number}|{kind:'rejected'; message:string};export const defaults = {title:'',items:[{name:''}],delivery:'pickup'} satisfies Draft;export function saveFixture(draft:Draft):Result { if (!draft.title.trim() || draft.items.length===0 || draft.items.some(i=>!i.name.trim())) return {kind:'rejected',message:'Missing required data'}; if (draft.items.some(i=>i.name.trim().toLowerCase()==='reserved')) return {kind:'rejected',message:'Item unavailable'}; return {kind:'saved',count:draft.items.length};}selectRow returns the original record or undefined, preserving extra fields such as stock. defaults uses satisfies to check the shape without replacing the inferred type with Draft; it is not runtime validation or a freeze. saveFixture is a synchronous mock of a business rule: missing data is rejected, Reserved is unavailable, and other nonblank records return a count. It accepts a typed Draft, not arbitrary JSON. A real server must parse unknown input, authenticate and authorize independently.
Connect a typed reducer to its context
import React,{createContext,useContext,useReducer} from 'react';import type {Dispatch} from 'react';type State={count:number};type Action={type:'add';amount:number}|{type:'reset'};function reducer(state:State,action:Action):State{ switch(action.type){case 'add':return {count:state.count+action.amount};case 'reset':return {count:0};default:{const missing:never=action;return missing;}}}const Store=createContext<{state:State;dispatch:Dispatch<Action>}|null>(null);function Controls(){const store=useContext(Store);if(!store)throw new Error('Missing Store provider');return <><p>{store.state.count}</p><button onClick={()=>store.dispatch({type:'add',amount:2})}>Add two</button><button onClick={()=>store.dispatch({type:'reset'})}>Reset</button></>;}export default function App(){const [state,dispatch]=useReducer(reducer,{count:0});return <Store.Provider value={{state,dispatch}}><Controls/></Store.Provider>;}The count starts at zero; Add two displays 2; Reset displays 0. The dispatch contract requires an amount only for add. A missing provider fails explicitly. This simple context deliberately recreates its value on each render; it does not promise optimal rendering. A typed query follows the same principle: model the returned data and error states from a validated API function; do not cast an unchecked response to the desired type. A discriminated union can represent pending, ready and failed states as in Chapter 29.
Practice
Reuse PickList for rooms with a capacity property, then try accessing stock on a room. Add a subtract action to the reducer and update the exhaustive switch. Check the standalone model with strict TypeScript before using it in a UI.