← Back to libraryQuestion 211 of 468
🔷TypeScriptBeginner

Type Inference

📌 Definition:

TypeScript automatically infers types from values and context, so you often don't need explicit annotations. let x = 5 is inferred as number without writing : number.

📖 Detailed Explanation:

Inference reduces boilerplate while keeping safety: the return type of a function, the type of a variable from its initializer, and array/object element types are all inferred. Contextual typing infers callback parameter types from where they're used (e.g. arr.map(x => ...) infers x). Best practice is to let TypeScript infer local variables and simple returns, but explicitly annotate PUBLIC function signatures and complex/exported types for clarity and to lock the contract. Over-annotating obvious types adds noise; under-annotating public APIs loses documentation value.

🔑 Key Points:
  • TS infers types from initializers and context
  • Contextual typing infers callback parameter types
  • Let locals infer; annotate public/exported signatures explicitly
  • Inference keeps code concise without losing safety
🌍 Real-World Example:

In arr.filter(u => u.active), TypeScript infers u as the user type from arr, so u.active autocompletes and a typo like u.activ is flagged — no annotation needed.

🎯 Scenario-Based Interview Question:

Should you annotate every variable, e.g. const count: number = items.length? Why or why not?