Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Cannot redeclare block-scoped variable' in unrelated files

Tags:

typescript

tsc

There is a simple TS package that is used as CommonJS modules and has no exports. TS files are compiled to JS files with the same name and used as require('package/option-foo').

tsconfig.json:

{   "compilerOptions": {     "target": "es5"   } } 

option-foo.ts:

declare const GlobalVar: any;  function baz() {}  if (GlobalVar.foo) GlobalVar.baz = baz; 

option-bar.ts:

declare const GlobalVar: any;  function baz() {}  if (GlobalVar.bar) GlobalVar.baz = baz; 

The important part here is that option-foo and option-bar are never used together. There are other complimentary TS files in the project, but they don't affect anything, just needed to be transpiled to JS in one tsc run.

When tsc runs, it throws

Cannot redeclare block-scoped variable 'GlobalVar'.

Duplicate function implementation.

Cannot redeclare block-scoped variable 'GlobalVar'.

Duplicate function implementation.

for GlobalVar and baz in both files.

How can this be treated without complicating build process or the output from these two TS files?

like image 371
Estus Flask Avatar asked Dec 01 '16 00:12

Estus Flask


People also ask

How do you block a scoped variable in Redeclare?

Conclusion # The error "Cannot redeclare block-scoped variable" occurs when we redeclare a variable in the same block or when TypeScript uses global typings, which interfere with local variable names. To solve the error, only declare a variable once in a block and use ES modules.

Which of the following is used to define block scoped variable in Javascript?

Variables declared using the const keyword are block scoped.


1 Answers

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.

like image 111
Daniel Rosenwasser Avatar answered Sep 20 '22 15:09

Daniel Rosenwasser