TypeScript BasicsCore· 25 min read

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.

No labels written — TypeScript infers them
let city = 'Pune';      // TS infers: string
let year = 2026;        // TS infers: number
let active = true;      // TS infers: boolean

year = 'next';          // error — year is a number

Note: 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:

The return type is inferred from the code
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

SituationLet TS infer?
Variable with an obvious starting valueYes — keep it clean
Function parametersNo — always type these
A variable declared empty (no value yet)No — add a type
Public function return types in big codeOften 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?

Answer: TypeScript infers the type from the value 0, so count is a number. Assigning a string to it later would be an error.

✍️ Practice

  1. Declare three variables with values but no type labels, then check what each infers by assigning a wrong value.
  2. Write a function half(n: number) with no return type and confirm TS infers number.

🏠 Homework

  1. Find two places in a small script where you could safely drop the explicit type and let inference do the work.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →