Advanced React 06 · Techniques
TypeScript for components
Components for the whole app: native element props, either–or props, generic components and types for hooks and reducers.
Loading lesson…
Advanced React 06 · Techniques
Components for the whole app: native element props, either–or props, generic components and types for hooks and reducers.
Loading lesson…
You've been using TypeScript since the start of the course. The table shows what you already know and where it was covered – we won't repeat it here:
| What you already know | Syntax | Where |
|---|---|---|
| a props type | interface CardProps { name: string; role?: string } | React basics 01 |
| content between the tags | children: ReactNode | React basics 02 |
| state with an empty initial value | useState<Item[]>([]) | React basics 04 |
| a ref to an element on the page | useRef<HTMLInputElement>(null) | Hooks 02 |
| reducer actions | type Action = { type: 'added' } | … | Hooks 03 |
| context | createContext<Value | null>(null) | Hooks 04 |
| data from outside | z.infer<typeof Schema> | Advanced React 02 |
This lesson is about what comes when you start writing components for the whole app – a button, a table, a picker that dozens of places will use. That's where you run into three new problems:
// 1) The button can only do what you listedinterface ButtonProps { label: string; onClick: () => void }<Button label="Save" type="submit" disabled /> // ❌ Button knows neither type nor disabled// 2) Props that contradict each otherinterface NoticeProps { message?: string; error?: Error }<Notice /> // ❌ nothing – and TypeScript doesn't object<Notice message="Saved" error={e} /> // ❌ both – which one should it show?// 3) A table for one kind of data onlyfunction UserTable({ rows }: { rows: User[] }) { … } // another copy for products…function AnyTable({ rows }: { rows: any[] }) { … } // …or any, and the types are gone
<button> – and that one has dozens of attributes (disabled, type, aria-label, title…). You can't list them by hand.any switches checking off entirely – a typo in a column name gets through.You can't push a British plug into a European socket – you can tell by the shape alone, without trying. A props type is the shape of a component's socket. Components for the whole app need smarter sockets: one that fits everything a plain button fits (section 1); one that, depending on a switch, accepts only one of two plugs (section 2); and a universal one that adapts to whatever you plug in (section 3).
| Problem | Solution | Section |
|---|---|---|
| your component should do everything a native element can | ComponentProps<'button'> & { … } | 1 |
| props belong together either–or | a discriminated union | 2 |
| a component for any data | a generic component <T> | 3 |
| a custom hook, reducer, context for the whole app | types in one place, the rest is inferred | 4 |
| derived types without copying | Omit, Pick, Partial, satisfies | 5 |
The table is a map of the lesson: the problem on the left, the solution in the middle, the section on the right.
You're writing your own Button with colour variants. Instead of listing attributes, you take the shape of the native socket (a native element = an element built into the browser, here the plain <button>) and add your own to it:
import type { ComponentProps } from 'react'type ButtonProps = ComponentProps<'button'> & { // everything <button> can do…variant?: 'primary' | 'ghost' | 'danger' // …plus my variant}function Button({ variant = 'primary', className = '', ...rest }: ButtonProps) {return <button className={`btn btn-${variant} ${className}`} {...rest} />}// usage – just like a plain button<Button type="submit" disabled={saving} aria-label="Save" onClick={save}>Save</Button>
import type imports just a type (TypeScript 01) – it disappears after the conversion to JavaScript.ComponentProps<'button'> = all the props a plain <button> has: attributes, events, ref, children. The angle brackets hold the HTML tag's name in quotes.& = "and at the same time": the resulting type has the native props and our variant....rest in the parameter collects everything we didn't take, and {...rest} passes it on to <button>. Including onClick, disabled and ref (in React 19 a ref is an ordinary prop, lesson Hooks 02).className = '' is a default value: when nobody sends className, it's an empty string. The string in backticks then joins our classes with the caller's (a template literal from JavaScript 01): variant="ghost" and className="wide" give "btn btn-ghost wide".When you don't want to allow some native attribute (say type, because the component decides it itself), remove it with Omit. Omit<Type, keys> takes a type and returns it without the listed properties:
// everything <button> can do, except typetype SubmitButtonProps = Omit<ComponentProps<'button'>, 'type'>function SubmitButton(props: SubmitButtonProps) {return <button type="submit" {...props} /> // the component decides type itself}<SubmitButton type="reset" /> // ❌ type isn't allowed here
The same works for 'input', 'a', 'div' and other tags. You'll find more helpers like this (Pick, Partial…) in section 5.
At the post office you fill in a form. At the top you tick whether you're sending a letter or a parcel – and depending on that you fill in different boxes. Anyone who ticks letter and fills in the parcel's weight has made a mistake. The discriminated union from lesson TypeScript 02 does exactly this for props:
// ❌ Both optional → you can pass both, or nothinginterface Props { href?: string; onClick?: () => void; children: ReactNode }// ✅ The "tick box" kind decides what else is requiredtype LinkOrActionProps =| { kind: 'link'; href: string; children: ReactNode }| { kind: 'action'; onClick: () => void; children: ReactNode }function LinkOrAction(props: LinkOrActionProps) {if (props.kind === 'link') {return <a href={props.href}>{props.children}</a> // TS knows: href is here}return <button onClick={props.onClick}>{props.children}</button> // and onClick here}<LinkOrAction kind="link" href="/cart">Cart</LinkOrAction> // ✅<LinkOrAction kind="link" onClick={pay}>Pay</LinkOrAction> // ❌ a link without href, with onClick
Inside the if, TypeScript knows which variant you have and lets you reach only its properties. From the outside you can't write a nonsensical combination.
One thing is different from usual: don't unpack the props right in the parameter. Writing function LinkOrAction({ kind, href, onClick }) doesn't work – href exists only in the link variant and onClick only in the action variant, so TypeScript won't let you pull them out "for every case". That's why you keep the whole props object and read the properties only inside the if, where it's clear which variant it is.
What you see: At the top, three buttons of our own Button component – with an icon, disabled with a native title, and with just an icon and aria-label. At the bottom, two variants of LinkOrAction.
Try it:
title attribute appears – it went through ...rest without us listing it.kind="link" and onClick. Uncommented, it would be an error.The takeaway: You inherit the native props with one line. A discriminated union guarantees the component always gets a sensible combination.
Loading the interactive part…
A vending machine doesn't know in advance what will be in it. Fill it with cans and it gives out cans; with biscuits, biscuits. And it won't give you a biscuit from the can machine. A generic component works the same way: it doesn't know in advance which data it will work with, but once you give it some, it "learns" their type and guards it. You know generics <T> from custom hooks (useLocalStorage<T>, Hooks 05): T is a placeholder name for a type that's filled in only when it's used. A component is just a function too, so it works the same way.
First, one helper: keyof from TypeScript 01 returns the names of a type's properties. For interface Product { id: number; name: string; price: number }, keyof Product is the same as 'id' | 'name' | 'price'. That's exactly what we want to guard in the table's columns: they may only be named like a real property.
interface Column<T> {key: keyof T & string // only a real property of T (see below)header: string // the text in the column headerrender?: (row: T) => ReactNode // optional: a custom look for the cell; the row arrives correctly typed}interface TableProps<T> {rows: T[] // the rows: an array of items of type Tcolumns: Column<T>[] // the columns for the same T}function Table<T>({ rows, columns }: TableProps<T>) {return (<table><thead><tr>{columns.map((col) => <th key={col.key}>{col.header}</th>)}</tr></thead><tbody>{rows.map((row, i) => (<tr key={i}>{columns.map((col) => (// the column's own render if it has one; otherwise the property's value turned into text<td key={col.key}>{col.render ? col.render(row) : String(row[col.key])}</td>))}</tr>))}</tbody></table>)}<Tablerows={products} // TypeScript works out: T = Productcolumns={[{ key: 'name', header: 'Name' },{ key: 'price', header: 'Price', render: (p) => `$${p.price}` }, // p is a Product{ key: 'color', header: 'Colour' }, // ❌ 'color' isn't a property of Product]}/>
<T> after the function name says: "this component has a type parameter, I don't know it yet".rows and works out that T is Product. The machine is filled.key in the columns must be a property of a product and render gets a Product.Three places in the table's code worth explaining:
keyof T & string: keyof T are the property names. The & ("and at the same time") adds the condition that the name is a string – in TypeScript, object properties can also be named with a number. We need a string because we use key as the key in JSX.row[col.key] reads the property whose name is in a variable (square brackets from JavaScript 03). For the column key: 'price' it's row.price.String(…) turns the value into text – the number 120 into "120". The table doesn't know which type the property has, and text can always be rendered.What you see: One Table component used twice: with products and with users. Columns with an arrow can be sorted.
Try it:
color column. If you uncommented it, TypeScript would underline it.The takeaway: The component is written once for any data. The data type is inferred from rows and guards the columns and the render functions.
Loading the interactive part…
A picker that returns the whole chosen item, not just its text, is written the same way:
interface SelectProps<T> {options: T[]value: NoInfer<T> // T is inferred only from options, not from valuegetLabel: (option: T) => string // what to showonChange: (option: T) => void // you get the whole item}function Select<T>({ options, value, getLabel, onChange }: SelectProps<T>) { … }<Select options={users} value={selected} getLabel={(u) => u.name} onChange={setSelected} /> // T = User
For code the whole app shares, a simple rule applies: write the types in one place and let the rest be inferred. Where exactly:
| What | Where to write the type | What is inferred |
|---|---|---|
| a custom hook returning a pair | return [on, toggle] as const | the pair type [boolean, () => void] |
| a reducer | the State and Action types (a discriminated union) | the state type and the allowed actions in dispatch |
| context | createContext<Value | null>(null) | the type in every component via a custom hook |
| a generic hook | function useLocalStorage<T>(key: string, initial: T) | T from the initial value |
// CartState and Product are made-up types: the cart's state { items: Product[] } and one producttype CartAction =| { type: 'added'; product: Product }| { type: 'removed'; productId: number }function cartReducer(state: CartState, action: CartAction): CartState { … }const [cart, dispatch] = useReducer(cartReducer, { items: [] })dispatch({ type: 'added', product }) // ✅dispatch({ type: 'remove', productId: 3 }) // ❌ a typo in type – TypeScript finds it at oncedispatch({ type: 'removed' }) // ❌ productId is missing
In an app you need the same data in several shapes. A user from the server has an id, the "New user" form doesn't have one yet (the server assigns it) and an edit sends only what changed. The simplest thing is to write three types by hand:
// ❌ Three almost identical types, each copied by handinterface User { id: number; name: string; email: string }interface NewUser { name: string; email: string } // the "New user" form – no id yetinterface UserChanges { name?: string; email?: string } // an edit – only what changed is sent
A month later the user gets a phone number. You have to add it in three places – and you'll forget one. TypeScript won't object, because the three types know nothing about each other. It's like three hand-copied copies of one form: it's better to have one original and a copier with settings such as "without the id box" or "everything optional".
TypeScript's built-in helpers are that copier. They are written like the generics from section 3: the helper's name and, in angle brackets, the type you start from and possibly the names of properties – as text in quotes, several of them separated by a vertical bar |. You name the result with type (lesson TypeScript 01) where types usually live: at the top of the file with the component, or in a shared types.ts file.
// ✅ One original, the rest is derived – the file src/types.tsexport interface User { id: number; name: string; email: string }export type NewUser = Omit<User, 'id'> // → { name: string; email: string }export type UserChanges = Partial<Omit<User, 'id'>> // → { name?: string; email?: string }
Now when a phone number is added to User, both derived types get it by themselves. The syntax Partial<Omit<User, 'id'>> is read from the inside out: first Omit throws out id, then Partial makes everything that's left optional. Now we'll go through the helpers one by one, each on a situation from a React app.
Omit<Type, keys> = "take the type and throw out the listed properties". It suits, for example, the form for a new user, where there's no id yet:
// the file NewUserForm.tsx – NewUser = Omit<User, 'id'> from the original abovefunction NewUserForm({ onSave }: { onSave: (user: NewUser) => void }) { … }onSave({ name: 'Anna', email: 'anna@example.com' }) // ✅onSave({ id: 1, name: 'Anna', email: 'anna@example.com' }) // ❌ there's no id in NewUser
Pick<Type, keys> is the opposite: "take only the listed properties". A card that shows just the name doesn't need the whole user – a piece is enough:
function UserCard({ user }: { user: Pick<User, 'name'> }) { // user must have at least namereturn <strong>{user.name}</strong>}<UserCard user={anna} /> // ✅ anna is a whole User – she has name, so she fits<UserCard user={{ name: 'Peter' }} /> // ✅ an object with just a name is enough too
A simple rule: Omit when you want almost everything; Pick when you want little. You've seen Omit in section 1 already – the SubmitButton without the type attribute.
Partial<Type> makes all properties optional (adds a question mark to them). The typical use is an edit: you send only what changed, but TypeScript still finds a typo in a property's name:
// updateUser = a made-up function that sends the changes to the serverfunction updateUser(id: number, changes: Partial<User>) { … }updateUser(1, { email: 'new@example.com' }) // ✅ only what changes is enoughupdateUser(1, {}) // ✅ even an empty object passes (nothing changes)updateUser(1, { emial: 'x' }) // ❌ a typo – there's no property emial in User
It's just as handy in a reducer action (lesson Hooks 03): { type: 'card_updated'; id: string; changes: Partial<Card> } – that's how the final project does it.
Record<Keys, Value> describes an object that has a value of the given type for every key. It helps most with a union type as the keys – say a table of colours for the tones of an alert:
type Tone = 'info' | 'danger'// One colour for every tone – a constant outside the componentconst toneColors: Record<Tone, string> = {info: 'blue',danger: 'red',}function Alert({ tone, children }: { tone: Tone; children: ReactNode }) {return <p style={{ color: toneColors[tone] }}>{children}</p> // find the colour by the tone}
Once you add 'success' to Tone, TypeScript underlines toneColors right away: it's missing a colour for success. You won't forget any tone. When you don't know the keys ahead (word counts, say), you write string instead of the union: Record<string, number>.
In section 1 you wrote ComponentProps<'button'> – an HTML tag's name in quotes. The same helper can take the props of a component too. That's handy when a library component doesn't export its props type and you want to wrap it:
import { Button } from 'some-library' // a made-up library that doesn't export its props type// My "Save" button: it can do everything the library's Button can, only the text is setfunction SaveButton(props: ComponentProps<typeof Button>) {return <Button {...props}>Save</Button>}
typeof Button in a type position means "the type of what's in the variable Button" – that is, the type of that component. You can tell the difference by the quotes: 'button' in quotes is an HTML tag, typeof Button without them is a component.
A size picker needs the list of sizes (to render the buttons) and a type (to guard the value). Writing both separately is copying again:
// ❌ The sizes twice: once as values, once as a typeconst sizes = ['S', 'M', 'L']type Size = 'S' | 'M' | 'L'
// ✅ The list once, the type is derived from itconst sizes = ['S', 'M', 'L'] as const // ① an array of exactly these stringstype Size = (typeof sizes)[number] // ② → 'S' | 'M' | 'L'// A size picker: buttons from the list, the type guards the valuefunction SizePicker({ value, onChange }: { value: Size; onChange: (size: Size) => void }) {return sizes.map((size) => (<button key={size} aria-pressed={size === value} onClick={() => onChange(size)}>{size}</button>))}<SizePicker value="M" onChange={setSize} /> // ✅<SizePicker value="XL" onChange={setSize} /> // ❌ XL isn't in the list
as const TypeScript would only say "an array of strings" (string[]) – anything can be in it. as const means "exactly these values and never others" (the array then can't be changed).typeof sizes is the type of the variable sizes. [number] after it means "the type of the item at any number index" – like sizes[0], sizes[1]… Together they give 'S' | 'M' | 'L'.'XL' to the array, it shows up in the type and in the buttons. The round brackets around typeof sizes just say what is worked out first.For constants such as a colour table or default settings you want two things: TypeScript should check the shape, and at the same time remember exactly what you wrote. A colon can only do the first:
type Setting = string | number | boolean // one setting: text, a number, or yes/no// ① with a colon: the shape is checked, but the variable's type is just "some settings"const a: Record<string, Setting> = { theme: 'light', fontSize: 16 }a.fontSize + 1 // ❌ an error – to TS fontSize is string | number | boolean, it doesn't know it's a numbera.fonSize // passes without an error! any text may be a key here, so the typo goes unnoticed// ② with satisfies: the same shape check, but the type stays exact { theme: string; fontSize: number }const b = { theme: 'light', fontSize: 16 } satisfies Record<string, Setting>b.fontSize + 1 // ✅ fontSize is a numberb.fonSize // ❌ an error – there's no such setting
And the third syntax, as, checks nothing at all – it just commands "trust me" (lesson TypeScript 01):
const c = { info: 'blue' } as Record<Tone, string> // passes even though the colour for danger is missing – the lie goes unnoticed
The table says when to use which; the syntax on the left, what it does in the middle, when on the right:
| Syntax | What it does | When |
|---|---|---|
const x: Type = … | checks it, and the variable has exactly that type | most places: props, state, parameters |
const x = … satisfies Type | checks it, but keeps the exact shape of the value | constants: colour tables, settings, route lists |
… as Type | checks nothing, just commands | only when you know more than TS (say e.target as Node in Hooks 05), never to silence an error |
All the helpers in one place; the syntax on the left, what it's for on the right:
| Syntax | What for |
|---|---|
Omit<User, 'id'> | almost the whole type – without the listed properties |
Pick<User, 'id' | 'name'> | only the chosen properties |
Partial<User> | all properties optional (for example data for an edit) |
Record<Tone, string> | an object with a value for every key – none gets forgotten |
ComponentProps<typeof Button> | the props of an existing component – even someone else’s from a library |
['S', 'M'] as const | an array with exact values; (typeof sizes)[number] turns it into a type |
… satisfies Type | checks the shape but keeps the exact type of the value |
This section puts the lesson together into templates to come back to when you write a component for many places. You'll find the same pattern in the Cheat sheets on the TypeScript in React tab.
import type { ComponentProps, ReactNode } from 'react'// ─── 1. A WRAPPER OF A NATIVE ELEMENT: a field with a label and an error (section 1) ───// everything <input> can do, plus a label and an optional errortype InputProps = ComponentProps<'input'> & { label: string; error?: string }function Input({ label, error, id, ...rest }: InputProps) {return (<><label htmlFor={id}>{label}</label>{/* ...rest = all the other props (name, type, onChange…) go on to the real field */}<input id={id} aria-invalid={error ? true : undefined} {...rest} />{error && <p className="field-error">{error}</p>}</>)}// use: <Input id="email" label="E-mail" type="email" error={errors.email} />// ─── 2. EITHER–OR PROPS: a button or a link (section 2) ───type ButtonOrLinkProps =| ({ as: 'button' } & ComponentProps<'button'>) // as="button" → the button's props| ({ as: 'link' } & ComponentProps<'a'>) // as="link" → the link's propsfunction ButtonOrLink(props: ButtonOrLinkProps) {// don't unpack props in the parameter – which variant it is only becomes clear hereif (props.as === 'link') {const { as, ...rest } = props // as doesn't belong on <a>: take it out, pass the rest onreturn <a {...rest} /> // TypeScript knows: rest are the link's props}const { as, ...rest } = propsreturn <button {...rest} /> // and here the button's props}// use: <ButtonOrLink as="link" href="/cart">Cart</ButtonOrLink>// ─── 3. A GENERIC COMPONENT: a list of anything (section 3) ───// T = the type of the items; TypeScript fills it in from itemsfunction List<T>({ items, renderItem, getKey }: {items: T[]renderItem: (item: T) => ReactNode // what one item looks like (a render prop)getKey: (item: T) => string | number // a stable key of the item (lesson React basics 02)}) {return <ul>{items.map((item) => <li key={getKey(item)}>{renderItem(item)}</li>)}</ul>}// use: <List items={users} getKey={(u) => u.id} renderItem={(u) => u.name} /> // T = User
ComponentProps and passes the rest on via ...rest.any anywhere.as only where you know more than TypeScript; otherwise : Type or satisfies.A warm-up on props types from lesson React basics 01: the type is written, the component just has to use it.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).Loading the interactive part…
The first challenge practises sections 1 and 3: extending a native button and a generic picker. The second practises section 4 – a typed reducer and context in which you catch a typo in an action name before you save the file.
The UI looks the same – the change is only in the types. The items below the example show whether every place has the right type. Which types the individual props have is in the comments in the code.
Medium and hard challenges unlock once you sign in. Like the whole course, they are free – just an e-mail, no password and no payment.
A discriminated union for actions + a typed context = you catch a typo in an action name before you save the file. What the types should guard is in the comments in the code.
Medium and hard challenges unlock once you sign in. Like the whole course, they are free – just an e-mail, no password and no payment.
ComponentProps<'button'> & { … } and ...rest – the component does everything the element does and you don't have to list anything.<T> learns the data type from its props and guards it; any switches checking off.satisfies instead of as.