Docs
/
TypeScript
Chapter 4
04 — Type Inference & Annotations
Core Concepts
- Type Inference — TypeScript automatically determines types from values
- Explicit Annotations — manually specifying types with
: Typesyntax - Contextual Typing — type inferred from where the expression appears (callbacks, etc.)
- const Assertions —
as constnarrows to the most specific (literal) type - satisfies Operator — validates type compatibility without widening (TS 5.0+)
- Return Type Inference — functions infer return types from return statements
- Best Common Type — TS picks the best type that fits all array elements
When to Annotate vs Infer
| Scenario | Annotate? | Why |
|---|---|---|
| Variable with initializer | No | Inferred from value |
| Function parameters | Yes | Can't be inferred |
| Function return type | Sometimes | Annotate public APIs |
| Object literals | Sometimes | Use satisfies for validation |
| Constants | No | Use as const for literals |
| Complex generics | Sometimes | Help TS when inference fails |