Home > Net >  How to check if a variable exists in TypeScript?
How to check if a variable exists in TypeScript?

Time:09-22

I have code that loops, and I want to initialize the variable one within the code. To do this, I check if the variable exists, and if not, initialize it.

In JavaScript, I would normally just do the following

if (typeof variableExample === 'undefined') {
    // run this code
}

But TypeScript doesn't like this. It tells me that it can't perform this because it cannot find the variable:

Any ideas for getting around this?

CodePudding user response:

To do this, I check if the variable exists, and if not, initialize it.

Variables that only conditionally exist aren't the TypeScript way, and it's generally not a good idea even in JavaScript.

There's a difference between declaring a variable (creating it, making it exist) and initializing the variable (giving it an initial value). TypeScript is complaining because you haven't declared the variable.

To solve that, declare it (let or const). If you really want the variable to start out with the value undefined, you can make that part of its type:

let testVar: undefined | number; // Initial value defaults to `undefined`,
                                 // though adding = undefined for clarity may
                                 // be good

(I think there's also a flag that lets you have undefined in its type implicitly, but I wouldn't use that flag.)

Then when your code is ready to see if it needs to set the value on it, it can use typeof testVar === "undefined" (or just testVar === undefined):

if (typeof testVar === "undefined") {
    testVar = 1;
}

...or the nullish coalescing operator:

testVar = testVar ?? 1;

Playground showing all three

But only do that if you really can't assign a meaningful value to the variable where you declare it, which is rare, and which in many cases should suggest to you that you need to put the variable in a narrower scope or otherwise refactor.

CodePudding user response:

If I understood your question correctly, I think a better approach to do this would be to first declare the variable outside of the loop and initialize inside if null or undefined

let myVar;
for(let i = 0; i < 10; i  ) {
  if(myVar == null) {
    myVar = 1
  }
}

Of course doing so in this example seems unnecessary but I hope it helps you map it to your use case

CodePudding user response:

A practical example of two variables and the use of typeof should be enough to know if a variable exists or not.

<script>
let x;

console.log(typeof x);  // <- declared variable
console.log(typeof y);  // <- undeclared variable

if(!x) console.log("x is null");
if(!y) console.log("y doesn't exists"); // Ooooopsss, ReferenceError
</script>

  • Related