During a design review, our design lead asked why a button component accepted five different prop shapes. The answer — badly scoped generics — is a red flag I've seen in almost every component library I've inherited.
I now treat TypeScript generics as promises. Each type parameter must map to a real constraint, and a consumer should be able to use the component without reading its implementation. If a generic doesn't make the call site safer or simpler, it doesn't belong there.
Here are the five patterns I actually use, from most to least common.
Rule zero: start concrete
Write the component with plain props first. Add a type parameter only when a real consumer needs a type to flow through the component — usually because the component accepts data and hands it back in a callback. If nothing flows through, you don't need a generic.
1. Generic data components (tables, lists, selects)
This is the pattern that pays for itself fastest. A table receives rows of some type T and hands each row back to render functions. Without a generic, those callbacks receive any.
import type { ReactNode } from 'react'
type Column<T> = {
key: keyof T & string
header: string
render?: (row: T) => ReactNode
}
type TableProps<T> = {
rows: T[]
columns: Column<T>[]
getRowId: (row: T) => string
}
export function Table<T>({ rows, columns, getRowId }: TableProps<T>) {
return (
<table>
<thead>
<tr>{columns.map((c) => <th key={c.key}>{c.header}</th>)}</tr>
</thead>
<tbody>
{rows.map((row) => (
<tr key={getRowId(row)}>
{columns.map((c) => (
<td key={c.key}>{c.render ? c.render(row) : String(row[c.key])}</td>
))}
</tr>
))}
</tbody>
</table>
)
}
The consumer never writes a type argument — TypeScript infers T from rows:
type User = { id: string; name: string; email: string; role: 'admin' | 'member' }
<Table
rows={users}
getRowId={(u) => u.id}
columns={[
{ key: 'name', header: 'Name' },
{ key: 'role', header: 'Role', render: (u) => u.role.toUpperCase() },
// { key: 'phone', header: 'Phone' } ← error: 'phone' is not a key of User
]}
/>
Rename a field on User and every table using it fails to compile. That's the promise kept.
2. Selects whose value type follows the options
A select's onChange should receive the same type as its options' values, not string:
type Option<V> = { label: string; value: V }
type SelectProps<V extends string | number> = {
options: readonly Option<V>[]
value: V
onChange: (value: V) => void
}
export function Select<V extends string | number>({ options, value, onChange }: SelectProps<V>) {
return (
<select
value={value}
onChange={(e) => {
const next = options.find((o) => String(o.value) === e.target.value)
if (next) onChange(next.value)
}}
>
{options.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
</select>
)
}
The constraint V extends string | number is the "real constraint" rule in action: an <option> value must be one of those, so the type says so.
3. Polymorphic components with an as prop
Design systems need a Button that can render as a link, or a Text that can be a p, span or label — while still type-checking the props of whatever element it becomes.
import type { ComponentPropsWithoutRef, ElementType } from 'react'
type ButtonTone = 'primary' | 'ghost'
type ButtonProps<T extends ElementType = 'button'> = {
as?: T
tone?: ButtonTone
} & Omit<ComponentPropsWithoutRef<T>, 'as'>
export function Button<T extends ElementType = 'button'>({ as, tone = 'primary', ...rest }: ButtonProps<T>) {
const Component: ElementType = as ?? 'button'
return <Component data-tone={tone} {...rest} />
}
<Button onClick={save}>Save</Button> // a <button>
<Button as="a" href="/pricing" tone="ghost">Pricing</Button> // an <a>; href is type-checked
<Button href="/pricing">Pricing</Button> // error: href doesn't exist on <button>
Two details matter here. The default (= 'button') means the common case needs no type ceremony, and Storybook examples compile untouched. And the Omit stops the component's own props from clashing with the element's.
Inside the component, Component is annotated as plain ElementType. Without that annotation TypeScript can't prove the rest props match an arbitrary T, and it reports a long error at the JSX line. The type safety lives in the public props, which is where callers need it.
Polymorphism is powerful but expensive for the compiler. Use it in a handful of base primitives (Box, Text, Button), not on every component.
4. const type parameters for literal configs
Sometimes you want TypeScript to keep the literal values you pass, not widen them to string. TypeScript 5.0's const modifier does that:
function defineTabs<const T extends readonly { id: string; label: string }[]>(tabs: T) {
return tabs
}
const tabs = defineTabs([
{ id: 'overview', label: 'Overview' },
{ id: 'billing', label: 'Billing' },
])
type TabId = (typeof tabs)[number]['id'] // 'overview' | 'billing'
Now a <Tabs activeId={…}> prop can be typed as TabId, and a typo like 'biling' is a compile error instead of a blank screen.
5. NoInfer to choose where inference comes from
When a type parameter appears in several props, TypeScript infers it from all of them — sometimes widening it in surprising ways. NoInfer (TypeScript 5.4) tells the compiler "don't infer from this one":
type SegmentedProps<V extends string> = {
options: readonly V[]
defaultValue: NoInfer<V>
}
function Segmented<V extends string>(props: SegmentedProps<V>) { /* … */ return null }
<Segmented options={['day', 'week', 'month']} defaultValue="year" />
// error: '"year"' is not assignable to '"day" | "week" | "month"'
Without NoInfer, TypeScript would happily widen V to include "year", and the bug would ship.
Habits that keep generics readable
-
Name parameters after what they mean when there's more than one:
TRow,TValue, notT,U. - Give defaults so the common case needs no type arguments.
-
Export helper types like
ButtonProps<T>andColumn<T>so consumers can build wrappers without re-deriving them. -
Test the types , not just the render. Add a file of
// @ts-expect-errorlines for calls that must fail; if one starts compiling, the test breaks. - Split when it grows. If the generic signature is longer than the component body, split it into a typed wrapper and a small view component. Reviews then focus on behaviour, not angle-bracket puzzles.
The button that once had five prop shapes now has one, with a default type parameter and an as prop. Marketing pages swap anchors in without losing type safety — and nobody has to read the implementation to use it.
Originally published at www.tayloramitverma.com.
Top comments (0)