question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Is there a way to use TypeScript to prevent accidental global access?

See original GitHub issue

I just spent 2 hours tracking down this issue:

  • We have a class with a prototype method called focus()
  • Our code was calling focus(), but it should have been calling this.focus()
  • The code compiled fine, because window.focus() shares the same signature as our focus() method

Is there a way to throw a compile time error when implicitly accessing global methods (on window, global, etc.)?

If not, a compiler flag would be extremely helpful. I would happily be more explicit about commonly used globals (window.setTimeout, window.document, …) if it meant I could more easily catch insidious bugs like this one.

Full commit here: https://github.com/coatue/SlickGrid/commit/0f8bab3fa9968173d749ccdf535c88f3a526ca8b.

Issue Analytics

  • State:open
  • Created 7 years ago
  • Reactions:106
  • Comments:47 (5 by maintainers)

github_iconTop GitHub Comments

36reactions
niieanicommented, Feb 26, 2017

How about adding a tsconfig.json option such as:

explicitGlobals: true

With it on, if you’d write name, location or focus() without being explicit, i.e. window.name, while at the same time, if those names aren’t declared in the local scope, it would mark those references as errors. At the same time there could be a quick fix to either reference the local scope, in case of a similar problem to @bcherny (missing this) or to reference the global scope explicitly, (i.e. name => window.name).

This would require being able to mark variables such as window, self and global as globals, instead of redefining each of their properties globally (as is currently done).

This would also mean that given the option is true, and one declared a $ global which is typeof jQuery, any usage would trigger the above error, unless you’d use it as window.$ or using import * as $ from 'jQuery'.

35reactions
jahoomacommented, Nov 12, 2019

Ok, while typescript is working on this, here’s a solution.

If you use eslint, you can just copy the below rule into your .eslintrc.

I left out some of the more commonly used variables like document, setTimeout, and addEventListener, but otherwise it is most of them.

“no-restricted-globals”: [“error”,“postMessage”,“blur”,“focus”,“close”,“frames”,“self”,“parent”,“opener”,“top”,“length”,“closed”,“location”,“origin”,“name”,“locationbar”,“menubar”,“personalbar”,“scrollbars”,“statusbar”,“toolbar”,“status”,“frameElement”,“navigator”,“customElements”,“external”,“screen”,“innerWidth”,“innerHeight”,“scrollX”,“pageXOffset”,“scrollY”,“pageYOffset”,“screenX”,“screenY”,“outerWidth”,“outerHeight”,“devicePixelRatio”,“clientInformation”,“screenLeft”,“screenTop”,“defaultStatus”,“defaultstatus”,“styleMedia”,“onanimationend”,“onanimationiteration”,“onanimationstart”,“onsearch”,“ontransitionend”,“onwebkitanimationend”,“onwebkitanimationiteration”,“onwebkitanimationstart”,“onwebkittransitionend”,“isSecureContext”,“onabort”,“onblur”,“oncancel”,“oncanplay”,“oncanplaythrough”,“onchange”,“onclick”,“onclose”,“oncontextmenu”,“oncuechange”,“ondblclick”,“ondrag”,“ondragend”,“ondragenter”,“ondragleave”,“ondragover”,“ondragstart”,“ondrop”,“ondurationchange”,“onemptied”,“onended”,“onerror”,“onfocus”,“oninput”,“oninvalid”,“onkeydown”,“onkeypress”,“onkeyup”,“onload”,“onloadeddata”,“onloadedmetadata”,“onloadstart”,“onmousedown”,“onmouseenter”,“onmouseleave”,“onmousemove”,“onmouseout”,“onmouseover”,“onmouseup”,“onmousewheel”,“onpause”,“onplay”,“onplaying”,“onprogress”,“onratechange”,“onreset”,“onresize”,“onscroll”,“onseeked”,“onseeking”,“onselect”,“onstalled”,“onsubmit”,“onsuspend”,“ontimeupdate”,“ontoggle”,“onvolumechange”,“onwaiting”,“onwheel”,“onauxclick”,“ongotpointercapture”,“onlostpointercapture”,“onpointerdown”,“onpointermove”,“onpointerup”,“onpointercancel”,“onpointerover”,“onpointerout”,“onpointerenter”,“onpointerleave”,“onafterprint”,“onbeforeprint”,“onbeforeunload”,“onhashchange”,“onlanguagechange”,“onmessage”,“onmessageerror”,“onoffline”,“ononline”,“onpagehide”,“onpageshow”,“onpopstate”,“onrejectionhandled”,“onstorage”,“onunhandledrejection”,“onunload”,“performance”,“stop”,“open”,“print”,“captureEvents”,“releaseEvents”,“getComputedStyle”,“matchMedia”,“moveTo”,“moveBy”,“resizeTo”,“resizeBy”,“getSelection”,“find”,“createImageBitmap”,“scroll”,“scrollTo”,“scrollBy”,“onappinstalled”,“onbeforeinstallprompt”,“crypto”,“ondevicemotion”,“ondeviceorientation”,“ondeviceorientationabsolute”,“indexedDB”,“webkitStorageInfo”,“chrome”,“visualViewport”,“speechSynthesis”,“webkitRequestFileSystem”,“webkitResolveLocalFileSystemURL”, “openDatabase”],

Read more comments on GitHub >

github_iconTop Results From Across the Web

Stop using `this` instead use `globalThis` for global variables
The problem is you have to remember to use the globals variable and you need to import or set it up somehow globally...
Read more >
How to avoid global variables in JavaScript? - Stack Overflow
The easiest way is to wrap your code in a closure and manually expose only those variables you need globally to the global...
Read more >
Documentation - Do's and Don'ts - TypeScript
Don't ever use the types Number , String , Boolean , Symbol , or Object ... Why: Using void is safer because it...
Read more >
10 Insights from Adopting TypeScript at Scale | Bloomberg LP
By adding just a single-line self-import to the top of ambient declaration files, you can prevent them from polluting the global namespace: ...
Read more >
JavaScript Best Practices — Things to Avoid | by John Au-Yeung
Like any other programming language, JavaScript has its own list of best practices ... We should avoid the use of global variables as...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found