1

TypeScript如何在模块中优雅地使用全局变量

 2 years ago
source link: https://xmanyou.com/typescript-using-global-variable-with-declare/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
4 November 2021 / typescript

TypeScript如何在模块中优雅地使用全局变量

用TypeScript编写js模块module时,经常遇到一种场景:需要使用在外部声明的全局变量。

这个全局变量可能是:

如果这个全局变量是在同一个工程里其他文件中声明的,我们可以直接通过import引入,但是这就增加了强依赖关系。

有时候我们不想增加这个依赖关系,或者,甚至无法提前得知这个全局变量是在哪里由谁声明的,是要怎么做呢?

使用declare关键字

declare var <全局变量>:<类型>;
declare const <全局变量>:<类型>;

如果不知道类型,可以使用any,或者省略。

这样就减少了依赖,降低了耦合度。

注意
这种情况下,在调用的时候,需要保证要使用的全局变量已经被声明并赋值,否则会报undefined。

阿斌

Read more posts by this author.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK