Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 96 ยท Getting Started

Variables and Scope in TypeScript

Learn how TypeScript handles var, let and const, block and function scope, hoisting and the temporal dead zone, uninitialized variables and definite assignment.

A variable is a named box for a value. In TypeScript the box also has a type: it says which values may go inside. The rules for where a variable exists, and for when it can be used, come straight from JavaScript. TypeScript adds checks on top, so many scope mistakes that would crash at runtime are reported while you type.

This lesson covers the three declaration keywords, the scope each one creates, hoisting, variables that start without a value and the ! assertion. If you already know JavaScript variables, the new part is how the compiler reasons about them.

Declaring variables: const, let and var

Use const by default. A const variable must be initialized and can never be reassigned. Use let when the value will change. Avoid var in new code.

TypeScript const, let and inferred types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Notice the inferred types. A const holding a string gets the literal type "TypeScript", because it can never change. A let holding a string gets the wider type string, because later assignments may differ. You can read more in Type Inference and Literal Types.

const stops reassignment, not mutation. A const array can still push, and a const object can still change its properties. For true immutability see readonly and immutability.

Block scope

let and const are block scoped: they exist only inside the nearest pair of curly braces. That includes if bodies, loops and bare blocks.

TypeScript Block scope and shadowing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Declaring a variable with the same name in an inner block is called shadowing. It is legal, but it can confuse readers. Many teams turn on the lint rule no-shadow.

Function scope and var

var ignores blocks. It is scoped to the whole function (or the module or script if declared at the top). That surprises people:

TypeScript var leaks out of blocks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The same code with let would be a compile error on both console.log lines. TypeScript does not forbid var, so rely on your linter (no-var) to keep it out. Another var quirk is redeclaration: var x = 1; var x = 2; is legal, whereas let x twice in the same scope is error TS2451.

The classic trap is closures in loops:

TypeScript The var-in-a-loop trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

With var there is a single i, and by the time the callbacks run it is 3. With let each iteration gets its own j.

Hoisting and the temporal dead zone

JavaScript moves declarations to the top of their scope before running the code. This is called hoisting, and each keyword behaves differently:

Keyword Hoisted? Value before the declaration line
var Yes undefined
let, const Yes, but not initialized Reading throws ReferenceError (the temporal dead zone)
function declaration Yes, with its body The function itself, callable early

TypeScript catches the obvious cases:

TypeScript
console.log(a); // error TS2448: Block-scoped variable 'a' used before its declaration.
let a = 1;

It cannot catch every case. If a function that reads a let variable is called before the variable is initialized, the compiler allows it, and the program throws at runtime:

TypeScript A temporal dead zone TypeScript cannot see

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The fix is to order your code so that data is initialized before the code that uses it runs. Putting constants at the top of a module is a good habit.

Global, module and function scope

At the top of a file, scope depends on whether the file is a module. A file with an import or export is a module, and its top-level variables are private to the file. A file with neither is a script, and its top-level declarations are shared globally with every other script in the project. That is why two script files both declaring const name = ... conflict with error TS2451.

The easy fix is to make every file a module. If a file has no imports or exports, add an empty export {}; at the end. Modern projects almost always use modules; see Modules.

Variables without a value

Sometimes a variable is declared first and assigned later. TypeScript tracks this with definite assignment analysis: it follows every path through your code and complains if you might read the variable before it was given a value.

TypeScript Definite assignment analysis

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Two ways to make the check pass: assign in every branch, or include undefined in the type and handle it:

TypeScript
let maybe: number | undefined;
console.log(maybe?.toFixed(1)); // undefined, no error

The definite assignment assertion

If you know a variable will be assigned before it is read, but the compiler cannot see it, write ! after the name:

TypeScript
let config!: { host: string };

initialize(); // assigns config somewhere the compiler cannot follow
console.log(config.host);

function initialize(): void {
  config = { host: 'localhost' };
}

The ! is a promise, not a check. If you break it, you get undefined at runtime. The class-field version of the same idea is in Classes.

Declaring variables the compiler cannot see

Occasionally a variable already exists at runtime, created by a script tag or the host environment, and TypeScript just does not know about it. declare tells the compiler that something exists without emitting any code:

TypeScript
declare const BUILD_VERSION: string; // injected by a bundler at build time
console.log(BUILD_VERSION);

This is the same mechanism used by declaration files.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What type does TypeScript infer for const mode = 'dark';?

    A const can never change, so TypeScript keeps the narrow literal type. A let would be widened to string.
  2. 2. Which keyword creates a variable that is visible outside the if block it was declared in?

    var is function scoped and ignores block boundaries. let and const are block scoped.
  3. 3. What happens if a function reads a let variable before the line that initializes it, and TypeScript cannot see the call order?

    The variable is in its temporal dead zone. TypeScript only reports the cases it can prove, so this one fails at runtime.
  4. 4. What does the ! in let value!: string; do?

    It is a definite assignment assertion: a compile-time promise with no runtime effect.

Summary

  • Prefer const, use let when you must reassign, and avoid var.
  • let and const are block scoped; var is function scoped and leaks out of blocks.
  • const fixes the binding, not the contents of an object or array.
  • let and const are hoisted but unusable until initialized (the temporal dead zone). TypeScript reports obvious violations only.
  • Definite assignment analysis rejects reads of variables that might not be assigned; use | undefined or the ! assertion when appropriate.
  • Files with import or export are modules with private top-level scope.

Next: Type Inference