简体   繁体   English

检查变量是否在 Typescript 中定义?

[英]Check if variable is defined in Typescript?

I'm trying to check if a variable is undefined using typescript but am not having any luck.我正在尝试使用 typescript 检查变量是否未定义,但没有任何运气。

I am currently trying我目前正在尝试

if (typeof variablename !== 'undefined') { /*do something here*/ }

but for some reason the compiler always gives me the error但由于某种原因,编译器总是给我错误

Cannot find name 'variablename'

I can pull up the browser console and paste the above code and it works as expected.我可以打开浏览器控制台并粘贴上面的代码,它可以按预期工作。 The file containing the undefined check exists in a file that is not imported by any other JS/TS file.包含undefined检查的文件存在于任何其他 JS/TS 文件未导入的文件中。

The TypeScript compiler won't let you access a variable it doesn't know about, since most of the time such accesses are errors. TypeScript 编译器不会让您访问它不知道的变量,因为大多数时候这种访问都是错误的。

If you want the compiler to believe that such a variable is in scope, you could declare it first:如果你想让编译器相信这样一个变量在 scope 中,你可以先declare

declare var variablename: string | undefined;
if (typeof variablename !== 'undefined') { /*do something here*/ }

That doesn't change the emitted JavaScript at all.这根本不会改变发出的 JavaScript 。 It just tells the compiler to act as if there is a var named variablename in scope whose type is string | undefined它只是告诉编译器就像在 scope 中有一个名为variablenamevar ,其类型为string | undefined string | undefined (in your use case it might be some type other than string but I needed an example). string | undefined (在您的用例中,它可能是string以外的其他类型,但我需要一个示例)。 In other words, it assumes that your JavaScript will run in a context where variablename of such a type is around.换句话说,它假设您的 JavaScript 将在这种类型的variablename名存在的上下文中运行。

This isn't exactly what you want, since it's possible at runtime that there is no such variable.这并不完全是您想要的,因为在运行时可能没有这样的变量。 Unfortunately there's no way to tell the compiler that the variable might be in scope and that typeof can be used to check it.不幸的是,没有办法告诉编译器该变量可能在 scope 中,并且可以使用typeof来检查它。 Variables are either in scope (and you can access them) or they're not (and you can't).变量要么在 scope 中(你可以访问它们),要么不在(你不能)。 There was a proposal at microsoft/TypeScript#23602 to have a way to conditionally declare variables, but nothing came of it.microsoft/TypeScript#23602上提出了一种有条件地声明变量的方法,但没有任何结果。 Declaring the variable as definitely-existing but of a type with | undefined将变量声明为绝对存在但类型为| undefined | undefined in it is as close as you can get, I think.我认为,其中| undefined的内容尽可能接近。

Playground link to code Playground 代码链接

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

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