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;
    };

})();
epitka
  • 17,275
  • 20
  • 88
  • 141
  • 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. – Ry- Apr 01 '13 at 16:36
  • 1
    The codegen for `module` is most similar to what you've posted – Ryan Cavanaugh Apr 01 '13 at 16:43
  • @minitech: No, it does not return function, it returns object literal. It is called revealing module pattern. See here: http://stackoverflow.com/questions/5647258/how-to-use-revealing-module-pattern-in-javascript – epitka Apr 01 '13 at 17:19
  • @epitka: Oh. Well that’s a module, not remotely a constructor. – Ry- Apr 01 '13 at 17:57
  • @minitech: What do you mean by "not remotely a constructor"? – epitka Apr 02 '13 at 15:08
  • @epitka: It’s not a function! There’s no constructor involved, so it couldn’t represent a class. – Ry- Apr 02 '13 at 23:01

1 Answers1

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
Ryan Cavanaugh
  • 209,514
  • 56
  • 272
  • 235
  • 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 – epitka Apr 02 '13 at 15:11