TS2454
TypeScriptERRORCriticalControl FlowHIGH confidence

Variable is used before being assigned

What this means

A variable is read, but TypeScript's control flow analysis cannot verify that it has been assigned a value.

Why it happens
  1. 1Declaring a variable without an initial value and then using it inside a conditional block that might not execute.
  2. 2Using a variable that is only assigned within a function that has not yet been called.
  3. 3A variable is declared, but its assignment happens in a later part of the code path.
How to reproduce

A variable is used before it is guaranteed to be assigned a value.

trigger — this will error
trigger — this will error
let value: string;
if (Math.random() > 0.5) {
  value = "hello";
}
console.log(value.toUpperCase());

expected output

error TS2454: Variable 'value' is used before being assigned.

Fix 1

Provide an initial value

WHEN A default or initial state is possible.

Provide an initial value
let value: string = "";
if (Math.random() > 0.5) {
  value = "hello";
}
console.log(value.toUpperCase());

Why this works

Initializing the variable ensures it always has a value.

Fix 2

Ensure assignment in all code paths

WHEN The logic must cover all possibilities.

Ensure assignment in all code paths
let value: string;
if (Math.random() > 0.5) {
  value = "hello";
} else {
  value = "world";
}
console.log(value.toUpperCase());

Why this works

Adding an 'else' block guarantees that 'value' is assigned in every case.

What not to do

Use the non-null assertion operator (!)

This tells the compiler to trust you that the value is not null or undefined, but it does not fix the underlying logical flaw and can lead to a runtime crash.

Sources
Official documentation ↗

microsoft/TypeScript src/compiler/diagnosticMessages.json

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All TypeScript errors