Variable is used before being assigned
A variable is read, but TypeScript's control flow analysis cannot verify that it has been assigned a value.
- 1Declaring a variable without an initial value and then using it inside a conditional block that might not execute.
- 2Using a variable that is only assigned within a function that has not yet been called.
- 3A variable is declared, but its assignment happens in a later part of the code path.
A variable is used before it is guaranteed to be assigned a value.
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.
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.
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.
✕ 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.
microsoft/TypeScript src/compiler/diagnosticMessages.json
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev