'Cannot redeclare block-scoped variable' in unrelated files

这一生的挚爱 提交于 2019-11-27 17:57:49

TL;DR Just write export {} in the outermost scope of your files.


At some point there needs to be a semantic disambiguation for whether a file should be treated as a module (and have its own scope) or a script (and share the global scope with other scripts).

In the browser, this is easy - you should be able to use a <script type="module"> tag and you'll be able to use modules.

But what about any other place that utilizes JavaScript? Unfortunately there isn't a standard way at this point to make that distinction.

The way that TypeScript decided to tackle the problem was to simply state that a module is any file which contains an import or export.

So if your file doesn't have any sort of top-level import or export statements, then you'll occasionally see issues with global declarations interfering with each other.

To get around this, you can simple have an export statement that exports nothing. In other words, just write

export {};

somewhere at the top-level of your file.

GlobalVar and the functions are exposed to the global namespace, and TypeScript is warning you that the variable and the method name are re-declared. Because the two function are declared in the global namespace, you only need to declare them one time.

If you want to do this, use namespaces.

namespace foo {    
    declare const GlobalVar: any;
    function baz() {}
}

namespace bar {
    declare const GlobalVar: any;
    function baz() {}
}

You can call the functions in the same way as you call them in C#, by using the namespace name: bar.baz or foo.baz.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!