In order to achieve this, I first verify if the variable exists; otherwise, I initialize it.
Having variables that only exist conditionally goes against TypeScript's principles and is generally not recommended even in JavaScript.
It's important to understand the distinction between declaring a variable (creating it) and initializing the variable (assigning an initial value). TypeScript points out that you haven't declared the variable.
To address this issue, declare the variable using let
or const
. If you wish the variable to initially hold the value undefined
, you can specify that as part of its type:
let testVar: undefined | number; // Initial value defaults to `undefined`,
// although adding = undefined for clarity might be beneficial
(There may be a flag allowing implicit inclusion of undefined
in its type, but I would refrain from using it.)
Then, when your code needs to determine whether to assign a value to the variable, check using
typeof testVar === "undefined"
(or simply
testVar === undefined
):
if (typeof testVar === "undefined") {
testVar = 1;
}
...or utilize the nullish coalescing operator:
testVar = testVar ?? 1;
Playground showcasing all three options
However, resort to those practices only if assigning a meaningful value at the variable's declaration point is truly impossible, which is uncommon and often signals the need for scoping adjustments or refactoring.