我应该如何告诉 Typescript 编译器有关在别处定义的全局变量的信息? [英] How should I tell the Typescript compiler about a global variable defined elsewhere?

查看:18
本文介绍了我应该如何告诉 Typescript 编译器有关在别处定义的全局变量的信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写 vanilla Javascript 并尝试通过指定 checkJs 标志在 VSCode 中使用 TS 类型检查.(这是过去一周的一次冒险!)

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!)

我的项目使用了 Webpack/Babel 捆绑的 ES6 模块;入口点 (app.js) 导出一个全局变量:

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

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

我告诉其他模块这个变量,所以 eslint 不会打扰我:

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

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

这工作正常,但现在 TS 检查器正在抱怨

This works fine, but now the TS checker is complaining

[js] Cannot find name 'viewer'.

如何告诉 TS 编译器我已经在当前文件之外定义了它?是否需要更新 TS 以遵守 eslint global 注释,或者它可能有自己的注释指令语法?

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?

推荐答案

TypeScript 绝对不尊重 eslint 注释,因为它是注释.要告诉 TS 一个外部变量可用,您可以简单地编写 declare let viewer: any;(或使用 const 而不是 let).

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).

这篇关于我应该如何告诉 Typescript 编译器有关在别处定义的全局变量的信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆