All posts

TypeScript patterns for flexible React components

9 min read
TypeScriptReact

Discriminated unions for variants, narrowing props with `as const`, and keeping ref/composition types honest.

Props that narrow themselves

Discriminated unions turn boolean soup into exhaustive switches. Pair `variant` props with `as const` on tuples when you need literal inference.

Composition over configuration

  • Split visual variants from behavioral ones.
  • Forward refs deliberately; document which DOM node you attach.
Shapes representing variants
Pull-right layout on desktop: text wraps beside the figure (float-based).

When a prop is only valid for one variant, nest it under that variant’s object type so misuse becomes a type error, not a runtime bug.

Refs and generics

  1. Use ElementRef<typeof Component> when you expose imperative handles.
  2. Avoid widening callback parameter types to `any`—use unknown + guards.
Layer diagram
Pull-left layout: pairs well with long explanatory paragraphs.

For public libraries, prefer stable minimal surfaces over kitchen-sink props—every optional flag is documentation debt.