Type Inference: TypeScript Guesses For You
You do not have to label everything — TypeScript often works out the type from the value itself.
What you will learn
- Understand how inference picks a type
- Know when to let TS infer and when to be explicit
- Spot inferred-type errors
TypeScript watches what you assign
You do not need a type on every variable. When you give a variable a starting value, TypeScript infers (figures out) its type automatically. This keeps your code clean while staying fully checked.
let city = 'Pune'; // TS infers: string
let year = 2026; // TS infers: number
let active = true; // TS infers: boolean
year = 'next'; // error — year is a numberNote: Output:
Error: Type 'string' is not assignable to type 'number'.
We never wrote : number, yet TypeScript inferred it from 2026 and still blocks the bad assignment.
Inference works on function results too
TypeScript can also infer what a function returns. Here it sees a number coming back, so the result is typed as a number:
function add(a: number, b: number) {
return a + b; // TS infers the return type: number
}
const total = add(2, 3); // total is inferred as number
console.log(total.toFixed(1));Note: Output:
3.0
Because a + b is a number, TypeScript knows add returns a number, so .toFixed(1) is allowed on total.
When to write the type anyway
| Situation | Let TS infer? |
|---|---|
| Variable with an obvious starting value | Yes — keep it clean |
| Function parameters | No — always type these |
| A variable declared empty (no value yet) | No — add a type |
| Public function return types in big code | Often yes, for clarity |
Watch out: Inference cannot read your mind for an empty variable. let x; becomes type any, which is unsafe — give it a type or a starting value.
Tip: A good habit: always type function parameters, and let TypeScript infer simple local variables. You get safety with less typing.
Q. You write let count = 0; with no type label. What type does TypeScript give count?
✍️ Practice
- Declare three variables with values but no type labels, then check what each infers by assigning a wrong value.
- Write a function
half(n: number)with no return type and confirm TS infers number.
🏠 Homework
- Find two places in a small script where you could safely drop the explicit type and let inference do the work.