Skip to main content
0 reactions

How TypeScript Infers a Variable’s Type

A card titled Type Inference, labelled TypeScript Basics, showing let pages = 320, pages = “many” failing with TS2322, and pages = 400 printing 400.
Type Inference: A variable gets its type from its first value.

You don’t have to write a type on every variable. When you give a variable a value, TypeScript works out its type from that value, which is called type inference. let pages = 320; makes pages a number, and tsc reports any later line that puts text in it.

Every command and output on this page is real, run with Node.js 26.13.1 and TypeScript 7.0.2 on macOS.

Syntax

SyntaxTypeScript
let name = value;
  • name: the variable.
  • value: its first value. Its type, such as number for 320, becomes the variable’s type.

See Type Inference (opens in a new tab) in the TypeScript handbook.

Prerequisites

The Example

A page count that starts as a number, and a later line that tries to put text in it. The file is pages.ts.

Step 1: Write the Code

pages.tsTypeScript
let pages = 320;

pages = "many";

Step 2: Check It with tsc

TerminalBash
tsc --noEmit pages.ts
OutputPlain text
pages.ts(3,1): error TS2322: Type 'string' is not assignable to type 'number'.

pages got the type number from 320, so tsc rejects the text at line 3, even though no type was written anywhere.

Step 3: Fix It

Give it a number instead, and print it:

pages.tsTypeScript
let pages = 320;

pages = 400;

console.log(pages);

Step 4: Check It and Run It

Check it again. No output means tsc found no errors:

TerminalBash
tsc --noEmit pages.ts

Then run it:

TerminalBash
node pages.ts
OutputPlain text
400

A new number fits the inferred type.

Common Mistakes

MistakeWhat happensDo this instead
Expecting const to take a new valuetsc reports error TS2588: Cannot assign to 'pages' because it is a constant.Use let for a value that changes
Leaving a function parameter without a typeThere’s nothing to infer from, so tsc reports error TS7006: Parameter 'name' implicitly has an 'any' type.Write the parameter’s type yourself

FAQ

Should I still write types on variables?

Not when the first value already says it. Write a type when a variable starts empty or should take more than one kind of value.

Conclusion

TypeScript infers a variable’s type from its first value, so let pages = 320 is a number from then on, and tsc catches anything else.

Additional Resources

TypeScript, Node.js and other names mentioned are trademarks of their respective owners.

0 comments