如何在 TypeScript 声明文件中定义一个单例 JavaScript 类
以下代码在我的 "test-file.js" 文件中,我想将其移植到 "test-file.d.ts" 文件中,以便我可以将其导入到 "test1.ts" 并针对 TypeScript 中的 JavaScript "类型" 进行编码。
我一直无法弄清楚如何在我的“test-file.d.ts”中以这样的方式定义下面的内容,以便 Typescript 中存在相同的实现。
(function(application) {
application.Message = function() {
this.m_messageContents = "New Message";
};
application.Message.prototype.getApplicationMessageContents = function() {
return this.m_messageContents;
};
application.SystemFactory = (function(){
var factory =
/**
* @lends application.SystemFactory
*/
{
createMessage: function() {
return application.Message();
}
};
return factory;
}());
}(application));
我不想将这个文件重新编码成 *.ts 文件,而是如上所述,我想将它导入到我的 "test1.ts" 中。
谢谢。
答案#1
让我看看这是否对你合适:
declare module application {
export class Message {
getApplicationMessageContents(): string;
}
export class SystemFactory {
static createMessage(): Message;
}
}
你可以这样使用:
let message = application.SystemFactory.createMessage();
let content = message.getApplicationMessageContents();
如您所见,您将把 static createMessage(): Message; 声明为静态,而不是声明类。
