TypeScript - Patterns & Best Practices

Prefer unknown over any

Use unknown + explicit narrowing instead of any.

Discriminated unions for states

type FetchState = { status: 'idle' } | { status: 'loading' } | { status: 'ok'; data: string } | { status: 'error'; error: string };

Branded types

type Brand = T & { __brand__: B };
type UserId = Brand;

function asUserId(s: string): UserId { return s as UserId }

Immutability defaults

  • Prefer readonly properties/arrays for value objects.
  • Use as const for literal configurations.

API design

  • Expose minimal surface area, document with types.
  • Prefer explicit return types for public functions.