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
let name = value;
name: the variable.value: its first value. Its type, such asnumberfor320, becomes the variable’s type.
See Type Inference (opens in a new tab) in the TypeScript handbook.
Prerequisites
- Node.js 24.12 or later, which runs TypeScript files directly. Install it from the Node.js download page (opens in a new tab).
- TypeScript, for the
tsccommand. Install it withnpm install -g typescript, as the TypeScript download page (opens in a new tab) shows.
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
let pages = 320;
pages = "many";
Step 2: Check It with tsc
tsc --noEmit pages.ts
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:
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:
tsc --noEmit pages.ts
Then run it:
node pages.ts
400
A new number fits the inferred type.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Expecting const to take a new value | tsc 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 type | There’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
- Type Inference (opens in a new tab) (TypeScript handbook)
- Everyday Types (opens in a new tab): type annotations on variables (TypeScript handbook)
TypeScript, Node.js and other names mentioned are trademarks of their respective owners.
0 comments