7

I have a piece of code that runs on the browser. There's a library loaded from a CDN that puts some variables on the global scope. How can I document the type of that variable?

For example

index.hmtl => puts globalVariable on the global scope

...
<script src="//cdn.library.com/library.js"></script>
...

index.js => uses globalVariable

/**
 * @type {SomeType} globalVariable
 */
const foo = globalVariable()

Something like that so I can specify the type of globalVariable. Is that possible?

Daniel Reina
  • 5,764
  • 1
  • 37
  • 50

1 Answers1

5

Typecasting and the window global can be your friend here.

To cast:

const globalVariable = /** @type {someType} */ (window.globalVariable);

To modify the window global add an externs file that contains:

/** @type {someType} */
window.prototype.globalVariable = function() {};
Graham P Heath
  • 7,009
  • 3
  • 31
  • 45
  • Awesome! It works! Just a minor detail, can you add "@type" before "{someType}" in the first code snippet? It may be also worth mentioning that it breaks [no-use-before-define](https://eslint.org/docs/rules/no-use-before-define) and it can be bypassed adding `// eslint-disable-line` at the end of the line. Thanks! – Daniel Reina May 27 '20 at 08:57
  • It seems `const foo = (foo)` results in `foo` being undefined. Had to do `const globalVariable = /** @type {someType} */ (window.globalVariable)`, so maybe the linting error was quite on point – Daniel Reina May 27 '20 at 09:03
  • Added `@type`, sorry about that. WRT the lint: I did wonder if that would be the case, but I figured that was a separate issue that was probably solvable by anyone asking this question... So good work, my faith in humanity is partially restored (no small feat). – Graham P Heath May 27 '20 at 14:59