Let's say my Typescript code uses a third-party namespace Foo
.
I want to write some utility functions for this module inside an Utility.Foo
module.
The problem is that the original Foo
would be hidden to functions defined inside Utility.Foo
.
In order to work around that, I want to write something like the following:
namespace Utility {
namespace _Foo {
export function bar() {
return Foo.x;
}
}
export {_Foo as Foo};
}
and it would be transpiled in ES3 into
var Utility;
(function (Utility) {
var _Foo;
(function (_Foo) {
_Foo.bar = function () {
return Foo.x;
};
})(_Foo || (_Foo = {}));
Utility.Foo = _Foo;
})(Utility || (Utility = {}));
Using the code above, I'm getting the error
TS1194: Export declarations are not permitted in a namespace
Why do I get this error?
What is the proper way to achieve that (if any)?
EDIT
As I commented in Paleo's answer , if I define my utility functions directly into Utility.Foo
, the original Foo
module is effectively hidden.
To understand why, let's look at the following Typescript code:
var Foo = { x : 42 };
namespace Utility {
export namespace Foo {
export function bar() {
return Foo.x;
}
}
}
It is transpiled to ES3 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 = {}));
If we look at how the Utility.Foo module is built, we can see that the Foo
accessible from the bar
function is in fact Utility.Foo = {}
. So bar
returns undefined
.
You can save the original value in a variable FooOrig
:
var Foo = { x: 42 };
const FooOrig = Foo;
namespace Utility {
export namespace Foo {
export function bar() {
return FooOrig.x;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.