TypeScript Type Inference
🧠 TypeScript Type Inference (Beginner → Advanced)
Type Inference in TypeScript means the compiler can automatically determine the type of a variable, function, or expression without you explicitly writing it.
This is one of TypeScript’s biggest strengths—less code, more safety.
1️⃣ What Is Type Inference?
Type inference is TypeScript’s ability to figure out types from values and usage.
✔ No need to write : number
✔ Still type-safe
2️⃣ Variable Type Inference ⭐
❌ Reassigning wrong type:
3️⃣ let vs const Inference ⭐ (Very Important)
let
const
✔ const infers narrower types
4️⃣ Function Return Type Inference ⭐
You can still be explicit:
✔ Both are valid
5️⃣ Function Parameter Inference 🔍
📌 Parameters usually need explicit types
📌 Return types are inferred
6️⃣ Array Type Inference ⭐
✔ Union types inferred automatically
7️⃣ Object Type Inference ⭐
Inferred as:
⚠️ Cannot add new properties:
8️⃣ Contextual Typing ⭐⭐
Type inferred from context.
✔ Common in callbacks & event handlers
9️⃣ Best Common Type Inference ⭐⭐
TypeScript finds the best common type
🔟 Type Inference with Generics 🔥
✔ Generic type inferred automatically
1️⃣1️⃣ When Inference Is NOT Enough ⚠️
any Inference (Bad)
Fix:
1️⃣2️⃣ Type Inference vs Explicit Types ⭐
| Situation | Recommended |
|---|---|
| Simple variables | Inference |
| Function return | Inference |
| Public APIs | Explicit |
| Complex objects | Explicit |
any inference | Avoid |
1️⃣3️⃣ Common Mistakes ❌
Relying on
anyOverusing explicit types
Forgetting
constfor literalsAssuming parameter types are inferred
Ignoring inference errors
📌 Interview Questions (Must Prepare)
What is type inference?
Difference between
letandconstinferenceWhen should you use explicit types?
What is contextual typing?
How does inference work with arrays?
Can TypeScript infer generic types?
✅ Summary
✔ TypeScript infers types automatically
✔ Reduces boilerplate code
✔ const creates literal types
✔ Inference works for variables, returns, arrays, objects
✔ Explicit types needed for APIs & clarity
✔ Core concept for clean & safe TypeScript
