This content originally appeared on DEV Community and was authored by Karandeep Singh
Today! We’re going to continue TypeScript learning like you’re a smart 5-year-old who loves to build things and asks “why?” (which is the best thing ever).
& yes “why?” is my way of learning.
I’ve divided this into 20 Chapters. and will go one by one and each will be of 2 – 3 min. of read.
This is a Continuation. if you have not read the Previous chapter – Chapter 6
Chapter 7: Type Inference – When TypeScript Thinks for You
Imagine This:
You say:
“Let’s play a game!”
And your friend immediately knows:
- It’s probably a board game
- Probably indoors
- Probably with snacks
You never told them all that, but they guessed from experience.
TypeScript does that too, it infers (guesses) the type when you don’t write it explicitly!
Example 1 – Simple variable
let age = 10;
You didn’t say : number
, but TypeScript knows age is a number.
So later:
age = "ten"; // ❌ ERROR! You can’t put a string here!
Example 2 – From functions
function double(x: number) {
return x * 2;
}
let result = double(5); // TypeScript infers result is number
Even though you didn’t write : number
for result
, TypeScript figured it out.
Example 3 – Arrays
let colors = ["red", "green", "blue"];
// Inferred as: string[]
colors.push("yellow"); // ✅
colors.push(123); // ❌ Nope!
Example 4 – Object Inference
let user = {
name: "Chatu",
active: true,
};
// Inferred as: { name: string; active: boolean }
But Sometimes You Gotta Be Explicit
If you say:
let guess; // 🤔 What is this?
guess = 5;
guess = "hello";
TypeScript says: “Okay, I give up. I’ll treat it as any
”
To avoid this, always assign immediately or give a type:
let guess: number;
Rule of Thumb:
Situation | What to Do |
---|---|
Simple value + assignment | Let TS guess (inference is great!) |
No value or complex shape | Be explicit (add types) |
Working in teams | Prefer clarity over guessing |
Summary
- TS can guess types for you (this is inference)
- It works best when you assign a value right away
- For tricky or empty variables, tell TS yourself
If you enjoyed this and want to master TypeScript and other technologies, follow the series and drop a like!
I’m a passionate software developer sharing the cool things I discover, hoping they help you level up on your coding journey.
How i created my own State Management Library : Rethinking State Management in React — From a Dev, for Developers.
This content originally appeared on DEV Community and was authored by Karandeep Singh