Variables in TypeScript
Learn Variables in TypeScript
Variables give names to values, while TypeScript tracks which kinds of values those names may hold.
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 variables in typescript.
- Predict the result of the complete runnable TypeScript example.
- Recognize one common mistake and correct it.
Understand the concept
let declares a reassignable binding; const declares a binding that cannot be reassigned. A type can be inferred from the initializer or explicitly annotated. Variables hold JavaScript values at runtime; the type checker tracks permitted assignments during development.
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
let score: number = 10;
score = score + 5;
const player: string = "Ravi";
console.log(`${player}: ${score}`);Verified output
Ravi: 15How 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
score starts at 10 and is reassigned to 15. player is initialized once with a string. The template literal reads the final values.
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
const does not freeze objects; it only prevents rebinding that variable. A separate lesson covers the differences among let, const and var.
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
Change the starting score and add another reassignment. Try score = "high" and read the checker message.
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
Variables in TypeScript: let declares a reassignable binding; const declares a binding that cannot be reassigned.
let creates a mutable binding; a const binding cannot be reassigned.
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.