给出以下TypeScript 2.1代码(snippet):
namespace outerNS {
export function fnMain() {
assertTrue(overloadedIdentifierNS.fnToBeCalled() === "intended");
}
namespace overloadedIdentifierNS {
export function fnToBeCalled() {
return "unintended";
}
}
}
namespace overloadedIdentifierNS {
export function fnToBeCalled() {
return "intended";
}
}
function assertTrue(v: boolean) {
if (!v)
alert("fail!");
}
如何从outerNS内部访问全局overloadedIdentifier.fnToBeCalled?
答案 0 :(得分:0)
浏览器中的所有全局属性都包含在Window
对象中,因此您可以这样做:
namespace outerNS {
export function fnMain() {
assertTrue(window.overloadedIdentifierNS.fnToBeCalled() === "intended");
}
...
}
...
这将在运行时工作,但编译器会抱怨:
Property' overloadedIdentifierNS'类型' Window'
上不存在
所以你可以这样做:
assertTrue(window["overloadedIdentifierNS"].fnToBeCalled() === "intended");
或者您可以扩充Window
对象:
interface Window {
overloadedIdentifierNS: {
fnToBeCalled: () => string;
}
}
namespace outerNS {
export function fnMain() {
assertTrue(window.overloadedIdentifierNS.fnToBeCalled() === "intended");
}
...
}
...