Reputation: 87
I'm trying to check if a variable is undefined using typescript but am not having any luck.
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.
Upvotes: 2
Views: 5483
Reputation: 327934
The TypeScript compiler won't let you access a variable it doesn't know about, since most of the time such accesses are errors.
If you want the compiler to believe that such a variable is in scope, you could declare
it first:
declare var variablename: string | undefined;
if (typeof variablename !== 'undefined') { /*do something here*/ }
That doesn't change the emitted JavaScript at all. It just tells the compiler to act as if there is a var
named variablename
in scope whose type is string | undefined
(in your use case it might be some type other than string
but I needed an example). In other words, it assumes that your JavaScript will run in a context where variablename
of such a type is around.
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. Variables are either in scope (and you can access them) or they're not (and you can't). There was a proposal at microsoft/TypeScript#23602 to have a way to conditionally declare variables, but nothing came of it. Declaring the variable as definitely-existing but of a type with | undefined
in it is as close as you can get, I think.
Upvotes: 7