简体   繁体   English

如何检查TypeScript中是否存在变量?

[英]How to check if a variable exists in TypeScript?

I have code that loops, and I want to initialize the variable one within the code.我有循环的代码,我想在代码中初始化变量 one。 To do this, I check if the variable exists, and if not, initialize it.为此,我检查变量是否存在,如果不存在,则对其进行初始化。

In JavaScript, I would normally just do the following在 JavaScript 中,我通常会执行以下操作

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

But TypeScript doesn't like this.但是 TypeScript 不喜欢这个。 It tells me that it can't perform this because it cannot find the variable:它告诉我它无法执行此操作,因为它找不到变量:

Any ideas for getting around this?有什么想法可以解决这个问题吗?

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.仅有条件存在的变量不是 TypeScript 方式,即使在 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. TypeScript 抱怨,因为您没有声明变量。

To solve that, declare it ( let or const ).要解决这个问题,请声明它( letconst )。 If you really want the variable to start out with the value undefined , you can make that part of its type:如果您真的希望变量以值undefined开头,则可以将该部分作为其类型:

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.) (我认为还有一个标志可以让您在其类型中隐式undefined ,但我不会使用该标志。)

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 ):然后,当您的代码准备好查看是否需要对其设置值时,它可以使用typeof testVar === "undefined" (或者只是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.但只有在您确实无法为声明它的变量分配有意义的值时才这样做,这很少见,并且在许多情况下应该向您建议您需要将变量放在更窄的 scope 或以其他方式重构。

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如果我正确理解了您的问题,我认为更好的方法是首先在循环外部声明变量并在nullundefined的情况下在内部初始化

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当然在这个例子中这样做似乎没有必要,但我希望它对你的用例有所帮助

A practical example of two variables and the use of typeof should be enough to know if a variable exists or not.两个变量的实际示例和 typeof 的使用应该足以知道变量是否存在。

 <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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM