简体   繁体   English

如何在打字稿声明文件中定义单例javascript类

[英]How to define a singleton javascript class in a typescript declaration file

The following code is in my "test-file.js" file, I want to port it into a "test-file.d.ts" file so that i can then import it into my "test1.ts" and code against the JavaScript "Types" in Typescript. 以下代码位于我的“ test-file.js”文件中,我想将其移植到“ test-file.d.ts”文件中,以便随后将其导入到我的“ test1.ts”中,并针对Typescript中的JavaScript“类型”。

I haven't been able to figure out how in my "test-file.d.ts" to define the below in such a way that the same implementation exists from Typescript. 我无法弄清楚在“ 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));

I do not want to re-code this file into a *.ts file, instead as stated above i want to import it into my "test1.ts". 我不想将此文件重新编码为* .ts文件,而是如上所述,我想将其导入到我的“ test1.ts”中。

Thanks. 谢谢。

Let me see if this is ok to you: 让我看看您是否可以:

declare module application {
    export class Message {
        getApplicationMessageContents(): string;
    }

    export class SystemFactory {
        static createMessage(): Message;
    }
}

And you can use like this: 您可以这样使用:

let message = application.SystemFactory.createMessage();
let content = message.getApplicationMessageContents();

As you can see, you will declare the static createMessage(): Message; 如您所见,您将声明static createMessage(): Message; as static and not the class. 作为静态而非类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM