0

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.

jcalz
  • 125,133
  • 11
  • 145
  • 170
wendtl
  • 37
  • 7
  • Does this help? https://stackoverflow.com/questions/43716263/how-to-check-undefined-in-typescript – Zac Anger Jan 16 '21 at 21:29
  • 2
    Is it really a browser error, or rather a typescript compile error? What does the compiled javascript look like? – Bergi Jan 16 '21 at 21:30
  • 2
    Does this answer your question? [How to check undefined in Typescript](https://stackoverflow.com/questions/43716263/how-to-check-undefined-in-typescript) – GBra 4.669 Jan 16 '21 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 Jan 16 '21 at 22:10

1 Answers1

3

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.

Playground link to code

jcalz
  • 125,133
  • 11
  • 145
  • 170