5

I want to convert some JavaScript code I've written into TypeScript. I'm rather new to TypeScript syntax and way of thinking, as a JavaScript developer.

What is giving me a headache is the hard time I've had to convert some piece of code that uses the Revealing Module Pattern into TypeScript.

One example is the below:

//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've thought was this:

//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's ugly.

Any suggestion how make this better?

2
  • What's wrong with making myFunction a private one? Commented Mar 26, 2015 at 9:50
  • You mean to make the myFunction a private one of the MyOtherConstructor? If that's the case, I can't because I want the myFunction to be used into the anonymous function code block independently. I don't want to create the obj first and then use the function from it. I want to use the myFunction as is into that code block and create a new obj object that has the myFunction method. It will be used later in code. Commented Mar 26, 2015 at 9:57

1 Answer 1

3

If you need a single object obj, then do not use a class. A namespace is more adapted:

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

If you prefer to keep the class, then here is a more concise code for it:

class MyOtherConstructor {
    constructor(public publicMethod: () => void) {
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.