TypeScript code similar to the structure of the module expansion template

I want to convert the JavaScript code that I wrote in TypeScript. I am more familiar with TypeScript syntax and thinking as a JavaScript developer.

What gives me a headache is a difficult time when I had to convert some piece of code that uses a drop-down module template in TypeScript.

The following is an example:

//JS Code
var obj;

//code...
(function(){
    function myFunction(){
        //do work
    }


    function MyOtherConstructor(){
        return {
            publicMethod: myFunction
        }
    }

    obj = new MyOtherConstructor();
})();

//use obj.publicMethod in code later

One workaround I thought:

//TypeScript code
var obj;

class MyOtherConstructor {
        private callback: any;
        constructor(f: any){
            this.callback = f;
        }
        publicMethod(): any{
            this.callback();
        }
}
//code...
(() => {
    function myFunction(){
        //do work
        console.log("Called myFunction");
    }
    obj = new MyOtherConstructor(myFunction);
})();

//use obj.publicMethod in code later

which works, but it is ugly.

Any suggestion on how to make this better?

+4
source share
1 answer

If you need one object obj, then do not use the class. The namespace is more adapted:

namespace obj {
    function myFunction() {
        // ...
    }
    export var publicMethod = myFunction;
}

, :

class MyOtherConstructor {
    constructor(public publicMethod: () => void) {
    }
}
+3

All Articles