Skip to content

Lesson 7 of 9 · 21m

Designing Component API Surfaces

Use union props, composition, and selective inheritance from native elements to build APIs that are strict without becoming hostile.

A typed component can be technically correct and still awful to use. The mature skill is designing the API surface: strict where mistakes are expensive, permissive where HTML already knows what it is doing, and boring everywhere else.

Inherit native props deliberately

type TextInputProps = Omit<React.InputHTMLAttributes<HTMLInputElement>, "size"> & {
  label: string;
  size?: "sm" | "md";
  error?: string;
};

This keeps placeholder, disabled, aria-describedby, autoComplete, and event handlers available without copying DOM types by hand. The Omit prevents a collision between the native size attribute and your design-system size scale.

Mutually exclusive props are a union

type EmptyStateProps =
  | { title: string; action: React.ReactNode; children?: never }
  | { title: string; children: React.ReactNode; action?: never };

That is more precise than optional props plus a runtime warning. The compiler becomes the first support engineer.

Composition often beats type complexity

Before making one component accept seventeen modes, ask whether two components would communicate better:

<Card>
  <CardHeader title="Usage" action={<ExportButton />} />
  <CardBody>...</CardBody>
</Card>

Composition gives TypeScript less magic to check and gives developers smaller concepts to learn. Use a mega-component only when coordination between pieces is genuinely internal.

Children deserve intent

children?: React.ReactNode is broad but often correct. Narrow it when the component has a real contract:

type ConfirmDialogProps = {
  children: React.ReactNode; // trigger content
  title: string;
  onConfirm: () => void;
};

Do not use JSX.Element unless you truly require exactly one element. ReactNode includes strings, fragments, arrays, null, and numbers — the actual shape of UI content.

Version the surface socially

Types catch misuse, but they do not explain migration. When a prop changes meaning, rename it rather than silently changing its type in a patch release. A compile error is helpful only when it points at intent.

Field notes

  • ComponentPropsWithoutRef<"button"> is usually better than hand-writing button props.
  • Beware spreading unknown props onto DOM elements; invalid attributes leak into the HTML.
  • Use aria-* props as part of the API, not an afterthought callers must discover.
  • The best component API feels obvious in plain TypeScript, not impressive in the type definitions.

Was this lesson helpful?

Sign in to rate