Suppose I am using a third-party namespace Foo
in my Typescript code.
I intend to create some utility functions for this module within a module called Utility.Foo
.
The issue here is that the original Foo
would be hidden from functions defined inside Utility.Foo
.
To overcome this issue, I am considering the following approach:
namespace Utility {
namespace _Foo {
export function bar() {
return Foo.x;
}
}
export {_Foo as Foo};
}
When transpiled to ES3, the above code results in:
var Utility;
(function (Utility) {
var _Foo;
(function (_Foo) {
_Foo.bar = function () {
return Foo.x;
};
})(_Foo || (_Foo = {}));
Utility.Foo = _Foo;
})(Utility || (Utility = {}));
I am encountering the following error when using the code above:
TS1194: Export declarations are not permitted in a namespace
Why does this error occur?
What is the correct way to achieve this (if any)?
UPDATE
As mentioned in Paleo's answer, if I define my utility functions directly within Utility.Foo
, the original Foo
module becomes effectively hidden.
To understand why, let's consider the following Typescript code:
var Foo = { x : 42 };
namespace Utility {
export namespace Foo {
export function bar() {
return Foo.x;
}
}
}
Its ES3 transpilation looks like this:
var Foo = { x: 42 };
var Utility;
(function (Utility) {
var Foo;
(function (Foo) {
function bar() {
return Foo.x;
}
Foo.bar = bar;
})(Foo = Utility.Foo || (Utility.Foo = {}));
})(Utility || (Utility = {}));
When examining how the Utility.Foo module is constructed, it is evident that the Foo
accessible within the bar
function is actually Utility.Foo = {}
. Hence, bar
returns undefined
.