TypeScript Best Practices
Production-ready TypeScript practices: naming, typing, error handling, and project structure.
What you'll learn
- When to annotate vs rely on inference for clean code
- Avoiding any and using unknown for safer runtime data
- Structuring types alongside source code for maintainability
- Using discriminated unions and branded types for domain modeling
Concept
Annotation Discipline
The best practice for annotations is: annotate public APIs (function signatures, exported types, class interfaces) and let inference handle local variables. Over-annotating clutters code; under-annotating public APIs makes them fragile. Function parameters always need annotations (no inference context). Return types on exported functions should be explicit — they serve as documentation and catch accidental changes. Internal locals like const result = compute(x) should rely on inference.
Avoid any, Embrace unknown
any disables type checking — it is a hole in your type system. Replace it with unknown for data of unknown type (API responses, parsed JSON). unknown forces you to verify the type before use, keeping safety. For runtime validation, use a library like zod that both validates data and infers TypeScript types from the schema. This gives you a single source of truth for both runtime and compile-time types.
Domain Modeling
Use discriminated unions to model domain states: type RequestState = Idle | Loading | Success | Error with a common status field. This makes impossible states unrepresentable — the compiler ensures you handle every case. Use branded types (also called opaque types) for domain identifiers: type UserId = string & { __brand: "UserId" } prevents mixing a UserId with a plain string. These patterns push more logic into the type system, catching bugs at compile time rather than runtime.
Example
// Best practice: discriminated union for state management.
type RequestState<T> =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; error: string };
function handleState<T>(state: RequestState<T>): string {
switch (state.status) {
case "idle": return "Ready to start";
case "loading": return "Please wait...";
case "success": return `Got: ${state.data}`;
case "error": return `Failed: ${state.error}`;
}
}
// Best practice: branded type for type-safe IDs.
type UserId = string & { readonly __brand: "UserId" };
function createUserId(id: string): UserId {
return id as UserId;
}
function getUser(id: UserId): string {
return `User ${id}`;
}
// Best practice: unknown for untrusted data.
function parseInput(raw: unknown): string {
if (typeof raw === "string" && raw.length > 0) {
return raw;
}
throw new Error("Invalid input");
}
const state: RequestState<number> = { status: "success", data: 42 };
const uid = createUserId("u123");
console.log(handleState(state));
console.log(getUser(uid));
console.log(parseInput("hello"));
Annotate public APIs, infer locals. Replace any with unknown for untrusted data. Use discriminated unions to model states and branded types for domain IDs. These practices catch bugs at compile time.
Try it
- JSON to TypeScript
Generate types from API responses as a starting point for domain modeling.
- JSON Schema Validator
Runtime validation complements compile-time types — validate before trusting.
- Code Diff
Compare best-practice code with common anti-patterns.
Common mistakes
The mistake
Using any as a quick fix for type errors
The fix
any creates a hole in your type system. Use unknown for untrusted data and proper types for everything else. If you must suppress, use @ts-expect-error so it is visible and tracked.
The mistake
Not using discriminated unions for state management
The fix
Model states as a discriminated union with a common status field. This makes impossible states unrepresentable and ensures exhaustive handling in switch statements.
The mistake
Duplicating type definitions instead of deriving them
The fix
Derive types with utility types (Pick, Omit, Partial) and from functions (ReturnType, Parameters). A single source of truth keeps types in sync with implementations.
Related Resources
Related Cheatsheets
- TypeScript Cheatsheet
Quick reference for all TypeScript syntax and patterns.
Practice TypeScript Best Practices
2 exercises
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.