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.
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
- Use ElementRef<typeof Component> when you expose imperative handles.
- Avoid widening callback parameter types to `any`—use unknown + guards.
For public libraries, prefer stable minimal surfaces over kitchen-sink props—every optional flag is documentation debt.