4

Is TypeScript not using revealing module pattern for classes? I expected different result from this code.

class Test {

    private privateProperty: any;

    public publicProperty: any;     
}

generates this:

var Test = (function () {
    function Test() { }
    return Test;
})();

I expected something like this:

var test = (function(){
    var privateProperty;
    var publicProperty;

    return {
        publicProperty: publicProperty;
    };

})();
6
  • No, it’s not. private/public checking is just done by the compiler and doesn’t influence generated code. (But that’s just a guess. :)) Your second example wouldn’t be right, though; it doesn’t even return a function. Commented Apr 1, 2013 at 16:36
  • 1
    The codegen for module is most similar to what you've posted Commented Apr 1, 2013 at 16:43
  • @minitech: No, it does not return function, it returns object literal. It is called revealing module pattern. See here: stackoverflow.com/questions/5647258/… Commented Apr 1, 2013 at 17:19
  • @epitka: Oh. Well that’s a module, not remotely a constructor. Commented Apr 1, 2013 at 17:57
  • @minitech: What do you mean by "not remotely a constructor"? Commented Apr 2, 2013 at 15:08

1 Answer 1

9

RMP is not appropriate for class-based design. module does what you want:

module myMod {
    var x = 31;
    export var y = x + 15;
}

Generates:

var myMod;
(function (myMod) {
    var x = 31;
    myMod.y = x + 15;
})(myMod || (myMod = {}));

Salient features here:

  • Privates are captured with a closure
  • Public members are visible as own properties of the object
  • The object is created in an IIFE
Sign up to request clarification or add additional context in comments.

1 Comment

I thought that "class" in typescript correlates to what I consider a class in c#, meaning private and public members etc., and module more like a namespace

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.