typescript-patterns
TypeScript Development Patterns
TypeScript patterns and best practices for building robust, type-safe, and maintainable applications. The compiler is most useful when it can prove your program's shape, so the guiding principle here is: push the type system to do real work instead of fighting it. This skill is the "how." For the "what" and "when" (the decisions about which pattern to reach for), see the TypeScript rules — rules/typescript/coding-style.md and rules/typescript/patterns.md in this repository, installed as rules/ecc/typescript/coding-style.md and rules/ecc/typescript/patterns.md.
When to Activate
- Writing new TypeScript or JavaScript code
- Reviewing a PR that touches
.tsor.tsxfiles - Refactoring existing TypeScript to remove
any, tighten types, or add strictness - Designing types, generics, or module boundaries for a new feature
- Setting up a new TypeScript project or upgrading
tsconfig.json - Debugging type errors that cascade through a codebase (usually a design problem, not an annotation problem)
Core Principles
1. Strict Mode Is the Baseline
strict: true (which enables strictNullChecks, noImplicitAny, strictFunctionTypes, and the rest) is not optional in a healthy codebase. If a codebase cannot compile under strict, that is a migration task, not an excuse to leave the flag off.
// tsconfig.json — a strict, discriminating baseline
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noImplicitOverride": true,
"noFallthroughCasesInSwitch": true,
"noPropertyAccessFromIndexSignature": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"forceConsistentCasingInFileNames": true,
"verbatimModuleSyntax": true
}
}noUncheckedIndexedAccess makes array and record access possibly-undefined, which surfaces a whole class of runtime crashes at compile time. If it produces too much noise, this is the pattern to add, not the flag to remove:
// If you have proven the index exists, lift the element into a local first.
const [first] = items
if (first === undefined) {
throw new Error("expected at least one item")
}2. any Is a Bug, Not a Tool
any disables the type system exactly where a bug is most likely to hide: at the boundary with untrusted or dynamic data. Prefer unknown and narrow it. When you truly need a fallback, prefer an explicit loosening with a comment over a silent any.
// Bad: any disables checking on the public API
export function parseConfig(raw: any): Config {
return raw.config ?? {}
}
interface Config {
timeout: number
retries: number
}
const DEFAULT_CONFIG: Config = { timeout: 30_000, retries: 3 }
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null
}
function toPositiveInt(value: unknown, field: string): number {
if (typeof value !== 'number' || !Number.isInteger(value) || value <= 0) {
throw new TypeError(`Expected ${field} to be a positive integer`)
}
return value
}
// Good: unknown forces safe narrowing at the edge. Every consumed field is
// validated with an explicit range, and defaults are declared up front.
export function parseConfig(raw: unknown): Config {
if (!isRecord(raw)) return { ...DEFAULT_CONFIG }
return {
timeout: raw['timeout'] === undefined ? DEFAULT_CONFIG.timeout : toPositiveInt(raw['timeout'], 'timeout'),
retries: raw['retries'] === undefined ? DEFAULT_CONFIG.retries : toPositiveInt(raw['retries'], 'retries'),
}
}3. Public APIs Get Explicit Types, Locals Get Inference
TypeScript infers local variables well. Exporting functions whose parameter and return types are implicit leaks inference decisions into every consumer and makes intent unreadable.
// Bad: exported API without explicit types
export function formatUser(user) {
return `${user.firstName} ${user.lastName}`
}
// Good: explicit public contract, inferred internals
interface User {
firstName: string
lastName: string
}
export function formatUser(user: User): string {
return `${user.firstName} ${user.lastName}`
}Type Design
Interfaces vs. Type Aliases
interface for object shapes that may be extended or implemented; type for unions, intersections, tuples, mapped types, and utility types. Prefer string-literal unions over enum unless you need runtime value enumeration or interop with code that requires it.
interface User {
id: string
email: string
}
type UserRole = 'admin' | 'member'
type AdminUser = User & { role: 'admin' }Discriminated Unions Are the Default State Machine
When a value can be in multiple shapes, model it as a discriminated union with a literal type/kind field. Exhaustive checking then becomes a free compiler feature: never a runtime fallback, always a compile error on a missing branch.
type Transaction =
| { kind: 'draft'; id: string }
| { kind: 'submitted'; id: string; submittedAt: Date }
| { kind: 'paid'; id: string; paidAt: Date; amountCents: number }
function describe(t: Transaction): string {
switch (t.kind) {
case 'draft':
return 'Saved but not sent'
case 'submitted':
return `Submitted on ${t.submittedAt.toISOString()}`
case 'paid':
return `Paid ${t.amountCents} cents on ${t.paidAt.toISOString()}`
default:
// exhaustive: any new member forces this to fail to compile
return ass