TypeScript Fundamentals
Type Inference & Annotations
TypeScript infers types from values, assignments, control flow, and usage. Annotations are most valuable at boundaries where they document intent and prevent accidental API drift.
- Inference is usually best for local values
- Annotations are valuable at boundaries
- Return annotations can prevent accidental widening
- Contextual typing flows inward
satisfieschecks without losing useful literals
| Location | Default choice | Why |
|---|---|---|
| Local const | Infer | Initializer is nearby |
| Function parameter | Annotate | Caller contract |
| Exported return | Often annotate | Public API stability |
| Callback parameter | Let context infer | Consumer API knows shape |
| Config object | Use satisfies | Check shape while preserving literals |
type User = { id: string; name: string }
export function formatUser(user: User): string {
const label = `${user.name} (${user.id})` // inferred string
return label
}
const routes = {
home: { path: "/", auth: false },
admin: { path: "/admin", auth: true },
} satisfies Record<string, { path: string; auth: boolean }>