[Discussion] Better Way to Declare Globals in JavaScript files
See original GitHub issueProblem
Using the new checkJs
feature, it is currently difficult to tell TypeScript about a global variable:
// @ts-check
myGlobal
window.myVar = 'foo';
The only way around this that I know is to create a .d.ts
file that defines these:
interface Window {
myVar: string;
}
declare var myGlobal: string;
JavaScript users should not have to write *.d.ts
files.
Possible Approaches
@egamma proposes that may be able to use the global
comment from ESlint http://eslint.org/docs/user-guide/configuring : /* global var1, var2 */
I’d also be interested to see if we could put type information in a jsdoc somehow, something like:
/**
* @global {string} myGlobal
*/
Issue Analytics
- State:
- Created 6 years ago
- Reactions:80
- Comments:40 (12 by maintainers)
Top Results From Across the Web
How to declare Global Variables in JavaScript - GeeksforGeeks
Global variables are declared at the start of the block(top of the program) · Var keyword is used to declare variables globally. ·...
Read more >How to declare a global variable in JavaScript - Stack Overflow
While it is possible to define a global variable by just omitting var (assuming there is no local variable of the same name),...
Read more >Where to put javascript as global function - Oracle Communities
Hi Gamez, You need to have something on the page templates - ideally, somewhere between the <head> and </head> tags and preferably ...
Read more >How the let, const, and var Keywords Work in JavaScript
As a JavaScript beginner, you probably learned how to declare variables and assign values. In the old, pre-ES6 era of JavaScript, ...
Read more >JavaScript Scope - W3Schools
A global variable has Global Scope: All scripts and functions on a web page can access it. Global Scope. Variables declared Globally (outside...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Why is that? Js users are already using dts files from @types; so does not seem totally foreign concept.
As a vanilla-JS user who just started using
checkJs
, it would be really nice if my eslint comment (/* global myVar */
) worked with TS so I didn’t have to document my global in two different ways for two different checkers. I hope that the TypeScript team supports the goal ofcheckJs
working on any valid JS without having to add a.d.ts
file to your build just to make the checker happy.