Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I tell the Typescript compiler about a global variable defined elsewhere?

I'm writing vanilla Javascript and trying to use TS type checking in VSCode by specifying the checkJs flag. (This has been something of an adventure over the past week!)

My project uses ES6 modules bundled by Webpack / Babel; the entry point (app.js) exports a global variable:

var viewer;
viewer = ...
window.viewer = viewer;

I tell other modules about this variable so eslint won't bother me:

/* global viewer */
var val = viewer.val;

This works fine, but now the TS checker is complaining

[js] Cannot find name 'viewer'.

How can I tell the TS compiler that I've defined this outside of the current file? Does TS need to be updated to respect the eslint global comment, or maybe it has its own comment directive syntax?

like image 654
Coderer Avatar asked Nov 07 '22 19:11

Coderer


1 Answers

TypeScript definitely does not respect the eslint note, since it is a comment. For telling TS that an external variable is available, you could simply write declare let viewer: any; (or with const instead of let).

like image 139
Stephan Avatar answered Nov 15 '22 11:11

Stephan