Type Inference
Question
When does TypeScript infer types?
Hint
TS infers from variable initializers, return statements, etc.
Explanation
TypeScript infers types when you do not explicitly annotate them. const x = 5 infers x as number. const s = "hi" infers string. Function return types are inferred from return statements. let x = [1, 2] infers number[]. Inference is contextual — the inferred type depends on how the value is used. You can override inference with explicit annotations. Inference is generally preferred for simplicity; annotations are for public APIs and when inference is too wide.
Related Resources
Related Lessons
- Type Inference
Learn inference.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.