Type Inference
Learn Type Inference
Type inference lets TypeScript determine many types from initializers and surrounding expressions.
In this lesson, you will study the rule, run a complete TypeScript example, explain its output, and test a small change.
What you’ll learn
- Explain the main rule behind type inference.
- Predict the result of the complete runnable TypeScript example.
- Recognize one common mistake and correct it.
Understand the concept
When you write const count = 5, TypeScript uses the initializer to determine a numeric type without needing : number. Function return types can often be inferred too. Inference is strongest when input information is clear; explicit types remain valuable for stable APIs or intentional unions.
See the concept visually
Use the diagram to locate the checks, values or branches involved in the example.
Run a complete TypeScript example
Save this code as main.ts or paste it into the TypeScript Playground. The example uses fixed values so it runs without prompting for input.
TypeScript code
const city = "Pune";
let visits = 1;
visits += 2;
console.log(`${city}: ${visits}`);Verified output
Pune: 3How to run locally: npx tsc --strict --target es2022 --module commonjs main.ts, then node main.js. When using a project configuration, run the matching project build instead.
Trace the execution
TypeScript infers the types of city and visits from the initial assignments. Incrementing visits by 2 is valid, and the string interpolation prints the new number.
Predict the output before you run the sample. Compare each line with the source expression that produced it, and distinguish the type checker’s work from what happens in JavaScript at runtime.
Common mistakes and how to avoid them
Inference does not predict real runtime strings or verify untrusted JSON. It only analyzes the source it can see.
Debugging habit: when a change is rejected, read the exact compiler diagnostic and inspect the operand types. When it compiles but behaves unexpectedly, follow the values through the JavaScript expressions.
Practice it yourself
Hover over both variables in an editor. Add visits = "three" and see which type was inferred.
Challenge: write down your prediction first, run the changed source, and explain any difference. Return to the verified version before continuing.
Check your understanding
Review the key idea
Type Inference: When you write const count = 5, TypeScript uses the initializer to determine a numeric type without needing : number.
The numeric initializer gives visits a number type.
Before continuing, be able to explain what is checked before execution and what actually changes at runtime in the example above.
Reaching the recap and completing the quizzes are separate milestones.