-
Notifications
You must be signed in to change notification settings - Fork 199
no-typeof-undefined should exclude globally declared variables like window #415
Comments
A linter for the OPPOSITE of this rule would be useful for globals! This is a common test in code that may run in a browser or under node.js, like server-side-rendered code. |
Does any object other than 'window' display this error? |
i.e. why should we change this rule for all globals instead of just window? |
@HamletDRC I'm misunderstanding, I suspect. AFAICT, this has nothing to do specifically with It's very easy to imagine analogous cases, though I confess I have no recent real-world one at hand. I think testing for some browser plugins used to sometimes use this, but global namespace pollution concerns made it now rare or extinct. |
Testing declare var fetch: any;
if (typeof fetch === "undefined") {
// Insert some polyfill
} |
OK, I did not know that server side JavaScript would throw an exception if you referenced an undefined global variable. |
@HamletDRC, In your browser dev tools, open a console and type
and press enter - you'll see that it's the same there. Be sure to spell it right ;-) |
OK, I had no idea. I wonder if there is an easy way to determine if something is global or not. |
@HamletDRC That's easy! If you don't know where it came from, it's global. |
Sorry, my last comment was thinking from a Javascript perspective, which may not be relevant in Typescript, since the dev provided a declaration somewhere, e.g. In the case of a global, there's no javascript backing the declaration, but I expect that you have no way of detecting that if the declaration is imported. TSLint just does static analysis of the Typescript source, right? |
I'm not sure, but I think something is global iff it is declared (using If any Typescript mavens see this, please confirm or deny. |
I've been using I'm curious to hear what value others see in |
@bradleyayers Related: https://stackoverflow.com/questions/3390396/how-to-check-for-undefined-in-javascript Could be wrong, but I believe the cases where, in Typescript, |
@estaub thanks for the link! I've written up a quick proposal for a new TypeScript feature related to this microsoft/TypeScript#23602. |
Adding a That will almost certainly take a very long time. Until then, accepting PRs to allow the user to add a whitelist of allowed variable names, e.g. |
☠️ It's time! ☠️ Per #876, this repository is no longer accepting feature pull requests. TSLint is being deprecated and we recommend you switch to https://typescript-eslint.io. Thanks for open sourcing with us, everyone! |
Bug Report
TypeScript code being linted
with
tslint.json
configuration:Actual behavior
TSLint gives error
The suggested fix would be:
which results in
ReferenceError: 'window' is undefined at...
Expected behavior
Ignore
typeof foo !== "undefiend"
whenfoo
has beendeclare
d globally.The text was updated successfully, but these errors were encountered: