Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Duplicate vars across multiple files allowed?

Tags:

typescript

Not sure if this is a bug in Typescript (2.1.5) or intended behavior, but if I have two files declaring the same block-level var in the same folder:

a.js

let x = 0;

b.js

let x = 1;

... and build it with tsc, I get:

a.ts(1,5): error TS2451: Cannot redeclare block-scoped variable 'x'.

b.ts(1,5): error TS2451: Cannot redeclare block-scoped variable 'x'.

Is this supposed to happen? Or does Typescript have the concept of a 'default' namespace, shared across the entire project?

I originally thought this may have something to do with Declaration Merging, but the equivalent using explicit namespaces seems to work fine:

c.js

namespace Test {
    let x = 0;
}

namespace Test {
    let x = 1;
}
like image 421
Lee Benson Avatar asked Jan 24 '17 13:01

Lee Benson


1 Answers

If you're not using a module system then you are declaring the same variable x in the global scope.
If you declare them in a module then it will be fine.

You're not getting any errors with the Test namespaces because of how that's compiled:

var Test;
(function (Test) {
    var x = 0;
})(Test || (Test = {}));
(function (Test) {
    var x = "fefe";
})(Test || (Test = {}));

As you can see, each variable is declared inside its own closure; the variables aren't declared into the namespaces.
If you do this:

namespace Test {
    export let x = 0;
}

namespace Test {
    export let x = "fefe";
}

you will get the same error, as it is compiled to:

var Test;
(function (Test) {
    Test.x = 0;
})(Test || (Test = {}));
(function (Test) {
    Test.x = "fefe";
})(Test || (Test = {}));

Edit

This is the intended behavior, the compiler stops you from unintentionally overriding a variable.
If you want to use the same variable in the global scope in a different file then you can do this:

// a.ts
var x = 1;

// b.ts
declare var x: number;
x = 3;
like image 168
Nitzan Tomer Avatar answered Oct 21 '22 13:10

Nitzan Tomer