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 piler 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.
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 piler 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.
- Does this help? stackoverflow./questions/43716263/… – Zac Anger Commented Jan 16, 2021 at 21:29
- 2 Is it really a browser error, or rather a typescript pile error? What does the piled javascript look like? – Bergi Commented Jan 16, 2021 at 21:30
- 2 Does this answer your question? How to check undefined in Typescript – GBra 4.669 Commented Jan 16, 2021 at 22:10
-
you can actually do simply
if (variablename !== undefined)
for the same effect. as for your question exactly, gonna need more code – D Pro Commented Jan 16, 2021 at 22:10
1 Answer
Reset to default 7The TypeScript piler 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 piler 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 piler 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 piler 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.
Playground link to code