• Error
  • Reported by the type checker

TS2454

Variable '{0}' is used before being assigned.

A variable is read on a path where it may not have been assigned yet. Initialise it where it is declared, or assign it on every path.

What it means

With strictNullChecks, the checker tracks whether a let variable without an initialiser has been assigned on every path before it is read. Reading it where some path skips the assignment is reported, because the value there is undefined.

Example

index.ts
declare const ok: boolean;
let message: string;
if (ok) {
  message = "done";
}
console.log(message);
ts-r-check -p tsconfig.json --pretty false ts-r output
index.ts(6,13): error TS2454: Variable 'message' is used before being assigned.

Recorded by node scripts/verify-examples.mjs with ts-r built from commit 6deaf01. The example uses the default tsconfig: strict, target: es2022, module: esnext, moduleResolution: bundler.

How to fix

  • Give the variable an initial value: let message = "".
  • Assign it in every branch (add the else).
  • If undefined is a valid state, say so in the type: let message: string | undefined.