我使用的内部模块(“AllianceModule”)分为两个文件。 第一个是在页面启动期间加载的。第二个是在需要时加载。 我将加载脚本过程从创建新的HTMLScriptElement更改为使用$ .ajax加载第二个脚本。 我这样做是为了在加载内部模块的第二部分时可以使用回调方法。此回调加载一个方法(称为“entryPoint”),该方法是第二个脚本的一部分。
Visual Studio编译好一切,程序运行正常。 从命令行运行ts-compiler
tsc References.ts --out main.js
其中references.ts包含页面启动期间所需的所有文件会出错:
C:\ sources \ TSProject \ Onload.ts(137,126):error TS2094:属性'entryPoint'在typeof AllianceModule'的值上不存在。
“entryPoint”是第二个模块的导出“静态”函数,不会从第一个模块内部调用。
我尝试添加
declare function entryPoint(allianceId: number, _parent: JQuery): void;
到内部模块,但编译器抛出相同的错误。创建一个接口并定义一个接口类型的var也没有用(但我怀疑我确实错误地尝试了这一点)。
如何声明方法,以便不再抛出错误(除了“强制转换”为任何方法然后调用方法)?
Onload.ts:
function onLoadDoThis()
{
//some code...
$("#aButton").click(function () { Scripts.scriptsAdmin.loadAndRun(3, 3, './Alliances.js', true, () => {(AllianceModule).entryPoint(0,null); } ); });
//more code
}
$(document).ready(onLoadDoThis);
AlliancesBase.ts文件包含
module AllianceModule {
//a lot of code always needed and thus loaded during startup
}
Alliances.ts文件包含
module AllianceModule {
//some alliances stuff only needed when the user does some specific actions
export function entryPoint(allianceId: number,_parent : JQuery) {
if (allianceId) {
console.log('EinzelAllianz');
(new AllianceDetails(allianceId)).allianceDetails(_parent);
}
else {
console.log("Alle Allianzen");
runTemplate();
}
}
}
我正在编译References.ts,其中只包含对OnLoad.ts和AlliancesBase.ts的引用。
PS:
第一个答案建议将declare函数放在模块中。这没有用,可能是因为我从模块外部调用方法(单击按钮事件)。我在声明后直接在AlliancesBase.ts中创建了一个转发方法:
declare function entryPoint(allianceId: number, _parent: JQuery): void;
export function entryPoint2(allianceId: number, _parent: JQuery) {
AllianceModule.entryPoint(allianceId, _parent);
}
这也没有用,因为我一直将entryPoint称为导出函数 - 编译References.ts文件时tsc编译器不知道这个导出函数。
答案 0 :(得分:0)
declare function entryPoint(allianceId: number, _parent: JQuery): void;
是否包含在模块中?如果没有,则表示全局entryPoint
函数,而不是AllianceModule中的方法。将其包裹在您声明它的module AllianceModule { ... }
中。