Skip to content
Tutorials Center
My learning

Topics

Lesson 95 of 132 ยท TypeScript with React

Generic Components and Advanced Types

Build reusable, type-safe React components with TypeScript generics. Learn generic lists, selects and tables, polymorphic as props, ComponentProps, ref types, satisfies and scalable patterns.

A button, a card and a text field are easy to type: you know exactly what props they take. The hard cases are the reusable components that work with any data: a list that renders users or products, a select that holds numbers or strings, a table whose columns depend on the row type, a Box that can be a div, a heading or a link. If you type their data as any, you lose every benefit of TypeScript. If you type them as one specific shape, they stop being reusable.

The answer is generics: a type parameter, written T, that is filled in by whoever uses the component, so the types flow through. This lesson shows generic lists, selects and tables, the polymorphic as prop, how to borrow the props of native elements with ComponentProps, the types of refs, the satisfies operator and a few patterns that keep type-heavy code readable as it grows. It follows TypeScript and React and Typing State, Refs, Context and Reducers.

All TypeScript here is read-only (tsx blocks), because the live editor strips no types and runs plain JavaScript. Each section therefore has a runnable JavaScript twin that shows the behaviour the types describe. A generic is erased when the code is built; what remains at runtime is a perfectly ordinary function.

What a generic is

A generic function or component has a type parameter, like a function parameter for types. Compare:

TSX
function firstOf<T>(items: readonly T[]): T | undefined {
  return items[0];
}

const a = firstOf([1, 2, 3]);        // a: number | undefined
const b = firstOf(['x', 'y']);       // b: string | undefined
const c = firstOf<boolean>([]);      // explicit: boolean | undefined

T is a placeholder. TypeScript looks at the argument, sees an array of numbers, infers T = number, and gives the result the right type. You hardly ever write <number> yourself. Generic components work the same way, with T appearing in the props.

A generic list

Say you want a List that handles empty states and keys, and lets the caller decide how each row looks. Rows can be any type:

TSX
import type { ReactNode } from 'react';

type ListProps<T> = {
  items: readonly T[];
  getKey: (item: T) => string | number;
  renderItem: (item: T, index: number) => ReactNode;
  emptyMessage?: string;
};

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

Use it with two different data types and nothing is repeated:

TSX
type User = { id: number; name: string };
type Product = { sku: string; title: string; price: number };

<List items={users} getKey={(user) => user.id} renderItem={(user) => user.name} />
<List items={products} getKey={(product) => product.sku} renderItem={(p) => `${p.title}: $${p.price}`} />

From items={users} TypeScript infers T = User, so inside the callbacks user is a User with autocomplete. Write renderItem={(user) => user.title} and the compiler says Property 'title' does not exist on type 'User'.

Two small syntax notes. In a .tsx file, a generic arrow function must be written const List = <T,>(props: ListProps<T>) => ...: the trailing comma stops the parser from reading <T> as a JSX tag. A plain function List<T>(...) declaration has no such problem, so prefer it. And a type parameter can be constrained with extends, so the component may assume something about T:

TSX
function IdList<T extends { id: string | number }>({ items }: { items: readonly T[] }) {
  return <ul>{items.map((item) => <li key={item.id}>{String(item.id)}</li>)}</ul>;
}

IdList accepts any object that has an id, and rejects objects without one. Here is the runtime of the earlier List; the same function serves two kinds of data, plus an empty case:

One generic list, three uses

Nothing in the function knows what a user or a product is. It only knows that it can call the two callbacks with whatever it holds, which is why one definition (and one type parameter) is enough.

A generic select

A select or radio group is a good second example, because there is a trap. A native <select> always reports its value as a string, even if the options were numbers. A generic component should hand the caller back the original value with its original type.

TSX
type SelectProps<T> = {
  label: string;
  value: T;
  options: readonly T[];
  getLabel?: (option: T) => string;
  onChange: (value: T) => void;
};

function Select<T>({ label, value, options, getLabel = String, onChange }: SelectProps<T>) {
  return (
    <label>
      {label}{' '}
      <select
        value={options.indexOf(value)}
        onChange={(event) => onChange(options[Number(event.target.value)])}
      >
        {options.map((option, index) => (
          <option key={index} value={index}>
            {getLabel(option)}
          </option>
        ))}
      </select>
    </label>
  );
}

The trick is to use the index as the DOM value and map it back to options[index]. T is then whatever the options are: Select with options={[1, 2, 3]} calls onChange with a number, and with options={['S', 'M', 'L']} with a string. If value and options disagree (a string value and number options) TypeScript reports an error, because both must be the same T. (With options.indexOf, comparison uses strict equality, so for object options pass the same object references, or add a getKey prop, as in List.)

A select that returns the original value

After choosing 3 as the quantity the log reads count -> 3 (number), a real number, while the browser's own select.value would have been the string "3". In TypeScript this is the reason onChange: (value: T) => void can honestly promise T.

A generic table with typed columns

A table is the classic reusable component whose column definitions depend on the row type. The simplest approach lets each column say how to render a row:

TSX
type Column<T> = {
  header: string;
  cell: (row: T) => ReactNode;
};

type TableProps<T> = {
  rows: readonly T[];
  columns: readonly Column<T>[];
  getRowKey: (row: T) => string | number;
};

function Table<T>({ rows, columns, getRowKey }: TableProps<T>) {
  return (
    <table>
      <thead>
        <tr>{columns.map((column) => <th key={column.header}>{column.header}</th>)}</tr>
      </thead>
      <tbody>
        {rows.map((row) => (
          <tr key={getRowKey(row)}>
            {columns.map((column) => <td key={column.header}>{column.cell(row)}</td>)}
          </tr>
        ))}
      </tbody>
    </table>
  );
}

A more compact API names a field of the row instead, { key: 'price', header: 'Price' }. Then key must be a real property of T. That uses keyof and a mapped type: for every key K of the row, build a column type for that key, and take the union of them.

TSX
type Column<T> = {
  [K in keyof T]-?: {
    key: K;
    header: string;
    format?: (value: T[K]) => ReactNode;   // value has the type of that field
  };
}[keyof T];

const columns: Column<Product>[] = [
  { key: 'title', header: 'Title' },
  { key: 'price', header: 'Price', format: (value) => `$${value.toFixed(2)}` },  // value: number
  { key: 'colour', header: 'Colour' },   // error: '"colour"' is not assignable to type '"sku" | "title" | "price"'
];

Read it slowly: [K in keyof T] loops over the row's keys; T[K] is "the type of field K"; [keyof T] at the end turns the object of column types into a union. The payoff is format: (value) => value.toFixed(2) knowing that value is a number because the key is 'price', and a typo in a key is an error. If this feels heavy, use the first, simpler version; clear code beats clever types.

A table driven by column definitions

The table prints Pen with $2.00 and Book with $12.50. At runtime nothing checks that key is valid: if you changed 'price' to 'cost', you would get a column of undefined. The TypeScript version rejects it before the code runs.

Polymorphic components: the as prop

A design system often wants one Text or Box component that can render as a p, h2, a or even your router's Link, while keeping the right props for each: href is allowed when as="a" and rejected when it is a div. This is a polymorphic component.

TSX
import type { ComponentPropsWithoutRef, ElementType, ReactNode } from 'react';

type BoxProps<E extends ElementType> = {
  as?: E;
  children?: ReactNode;
} & Omit<ComponentPropsWithoutRef<E>, 'as' | 'children'>;

function Box<E extends ElementType = 'div'>({ as, children, ...rest }: BoxProps<E>) {
  const Component: ElementType = as ?? 'div';
  return <Component {...rest}>{children}</Component>;
}

<Box>plain div</Box>
<Box as="h2">a heading</Box>
<Box as="a" href="/docs">a link</Box>
<Box as="button" type="submit" disabled>a button</Box>
<Box href="/docs">oops</Box>            // error: 'href' does not exist on type ... (a div has no href)
<Box as="a" hrf="/docs">typo</Box>      // error: 'hrf' does not exist

ElementType means "any tag name or component". The type parameter E is inferred from the as prop, and ComponentPropsWithoutRef<E> looks up the props that element accepts. Omit removes the two names we define ourselves, so they cannot clash. The default = 'div' handles the case with no as. We use ComponentPropsWithoutRef here because in React 19 ref is an ordinary prop, so you can add ref?: Ref<...> yourself if you need it.

Polymorphic types are the most advanced typing in this lesson, and they get complicated quickly (in particular when as is a custom component). For application code, a few separate components (Heading, Link, Button) are often clearer. Reach for as in design-system primitives, and consider tested libraries before inventing your own.

At runtime, as is only a variable that holds a tag name or component. The component below renders the same content as different elements, and uses a custom component as well:

An as prop at runtime

The report line reads Rendered tags: DIV, H3, A, A: the same Box produced a div, a heading and two anchors (the last one through FancyLink). In TypeScript, each usage is checked against the props of its own element.

Borrowing props with ComponentProps

When your component wraps a native element, do not retype every attribute. Reuse them:

TSX
import type { ComponentProps } from 'react';

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

function Button({ variant = 'primary', loading = false, disabled, children, ...rest }: ButtonProps) {
  return (
    <button type="button" {...rest} disabled={disabled || loading} data-variant={variant}>
      {loading ? 'Loading...' : children}
    </button>
  );
}

<Button onClick={save} aria-label="Save draft" form="draft-form">Save</Button>   // all native props accepted

ComponentProps<'button'> is every prop a <button> accepts, including onClick, disabled, aria-* and, in React 19, ref. Your own props are added with &. The rest of the props are spread onto the real element, so the wrapper stays a thin layer. Related helpers:

Type Gives you
ComponentProps<'input'> Props of a built-in element, including ref
ComponentPropsWithoutRef<'input'> Same, without ref
ComponentProps<typeof Card> Props of one of your own components
Omit<ComponentProps<'button'>, 'type'> The props minus the ones you take control of
Parameters<typeof fn> / ReturnType<typeof fn> The argument and result types of a function

Be careful about the order of spreading. {...rest} before your own attributes lets you protect them (disabled above cannot be overridden by the caller), and after lets callers override. Decide on purpose.

A button that forwards the rest of its props

The report shows that aria-label reached the DOM, variant became a data attribute and loading disabled the third button, which now says "Loading...". Callers wrote only the props they cared about.

Ref types

In React 19, a ref is a normal prop, so type it as Ref<ElementType>:

TSX
import { useImperativeHandle, useRef } from 'react';
import type { Ref } from 'react';

type PlayerHandle = {
  play: () => void;
  pause: () => void;
};

function Player({ ref }: { ref?: Ref<PlayerHandle> }) {
  const videoRef = useRef<HTMLVideoElement>(null);
  useImperativeHandle(ref, () => ({
    play: () => void videoRef.current?.play(),
    pause: () => videoRef.current?.pause(),
  }));
  return <video ref={videoRef} />;
}

function Page() {
  const playerRef = useRef<PlayerHandle>(null);
  return (
    <>
      <Player ref={playerRef} />
      <button type="button" onClick={() => playerRef.current?.play()}>Play</button>
    </>
  );
}

The type argument of the ref says what the parent receives. For a plain forwarded DOM node that is the element (Ref<HTMLInputElement>); with useImperativeHandle it is the small object you chose to expose, which is better encapsulation. See Refs and Imperative Handles.

satisfies, as const and deriving types from data

Instead of writing a type and then data that matches it, you can let the data be the source of truth.

TSX
const variants = {
  primary: { background: '#2563eb', color: '#fff' },
  ghost: { background: 'transparent', color: 'inherit' },
  danger: { background: '#dc2626', color: '#fff' },
} satisfies Record<string, { background: string; color: string }>;

type Variant = keyof typeof variants;     // 'primary' | 'ghost' | 'danger'

function Chip({ variant }: { variant: Variant }) {
  return <span style={variants[variant]}>{variant}</span>;
}

satisfies checks that the object matches the shape you describe (a typo like colour is an error) without widening it to that shape. The object keeps its precise keys, so keyof typeof variants is a real union, and adding a warning entry updates the Variant type everywhere. Compare with a type annotation const variants: Record<string, ...>, which would forget the keys and make Variant just string.

as const makes a value read-only with literal types, useful for lists of options:

TSX
const sizes = ['small', 'medium', 'large'] as const;
type Size = (typeof sizes)[number];   // 'small' | 'medium' | 'large'

Now the array drives both the dropdown choices at runtime and the allowed values at compile time, with no chance of the two drifting apart.

Utility types for props

A few built-in helpers cover most day-to-day needs:

TSX
type User = { id: number; name: string; email: string; admin: boolean };

type UserSummary = Pick<User, 'id' | 'name'>;            // only those fields
type UserFormValues = Omit<User, 'id' | 'admin'>;        // everything except
type UserPatch = Partial<User>;                          // every field optional
type FullUser = Required<Partial<User>>;                 // every field required again
type UsersById = Record<number, User>;                   // object keyed by id
type AdminFlag = User['admin'];                          // boolean (indexed access)
type FrozenUser = Readonly<User>;                    // fields cannot be reassigned

For props, Pick and Omit are the workhorses: derive a card's props from the model it shows instead of copying fields. Then renaming a field in User updates the card automatically.

Patterns that scale

  • Start concrete, generalize when the second use appears. Write the list for users; when products need it too, turn User into T.
  • Few type parameters. One T (maybe two) is readable. Four generic parameters with constraints is a sign the component does too much.
  • Constrain only as much as the component needs. T extends { id: string | number } is a promise the component actually uses.
  • Derive, do not repeat. Use typeof, keyof, Pick, Omit, ComponentProps and satisfies so one change flows everywhere.
  • Prefer unions and composition over piles of booleans. variant: 'primary' | 'ghost' beats isPrimary and isGhost. Several booleans permit combinations that mean nothing.
  • Export prop types (export type ButtonProps) so other files can extend them.
  • Keep the public type simple, the private implementation honest. It is acceptable for the inside of a tricky polymorphic component to use one cast, if the public signature is correct and tested.
  • Read the error from the bottom. For long TypeScript errors the last lines often hold the actual difference ("Type 'string' is not assignable to type 'number'").
  • Test your types where it matters (// @ts-expect-error above a line that must fail), as shown in Testing React Components.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In <List items={users} getKey={(u) => u.id} renderItem={(u) => u.name} />, how does TypeScript know u is a User?

    The type parameter T is inferred from the items prop, then used for the callbacks' parameters. You rarely need to write the argument by hand.
  2. 2. Why does the generic Select use the option index as the DOM value?

    The demo logged count -> 3 (number). Mapping the string index back to options[index] preserves the caller's type.
  3. 3. What does Omit<ComponentPropsWithoutRef<E>, 'as' | 'children'> do in the Box props?

    It borrows the native element's props, such as href for a, while preventing a clash with the component's own as and children.
  4. 4. What is the advantage of satisfies over a plain type annotation on the variants object?

    An annotation like Record<string, ...> would widen the keys to string. satisfies checks without widening.
  5. 5. In the Column<T> mapped type, why does format: (value) => value.toFixed(2) work for the price column?

    Each column type is built per key, linking key: K to format: (value: T[K]) => ..., so the callback sees that field's type.

Summary

  • A generic component takes a type parameter T that is inferred from its props, so lists, selects and tables stay reusable and fully typed.
  • In .tsx, prefer function Name<T>() declarations; constrain with extends only what the component uses.
  • Keep the caller's value types intact: map from a DOM index back to the original option instead of trusting strings.
  • A polymorphic as prop combines ElementType, ComponentPropsWithoutRef<E> and Omit; use it in design-system primitives, not everywhere.
  • Borrow native props with ComponentProps<'button'>, add your own with &, and spread the rest.
  • Type refs with Ref<T> (a plain prop in React 19); useImperativeHandle exposes only a small, typed handle.
  • Let data drive types with satisfies, as const, typeof and keyof; use Pick, Omit, Partial, Record to derive props.
  • Keep generics simple and readable: start concrete, generalize on the second use.

Next: UI Libraries and Design Systems