Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I declare local variables and functions within a TypeScript class?

In TypeScript, I can't seem to declare a function in a class without the compiler adding it to the prototype. For example:

class MyTypeScriptClass {
    // method, is added to prototype
    foo1(): void {
        alert('invoked foo1');
    }

    // private method also added to prototype
    private foo2(): void {
        alert('invoked foo2');
    }

    //// can I have a local function, without making it a private method?
    //function foo3() {
    //    alert('invoked foo3');
    //}
}

The above compiles to this:

var MyTypeScriptClass = (function () {
    function MyTypeScriptClass() { }
    MyTypeScriptClass.prototype.foo1 = function () {
        alert('invoked foo1');
    };
    MyTypeScriptClass.prototype.foo2 = function () {
        alert('invoked foo2');
    };
    return MyTypeScriptClass;
})();

What I am looking for is typescript that can compile to the following JavaScript:

var fvm = new FlasherViewModel2();
    var MyTypeScriptClass = (function () {
        function MyTypeScriptClass() { }
        MyTypeScriptClass.prototype.foo1 = function () {
            alert('invoked foo1');
        };
        MyTypeScriptClass.prototype.foo2 = function () {
            alert('invoked foo2');
        };
        function foo3() {
            alert('invoked foo3');
        }
        return MyTypeScriptClass;
    })();

Can it be done?

(As a side note, I know that foo3 would not be callable from external code. I would actually invoke foo3 from another method within the class, for example, to pass a function to a jQuery fadeOut.)

like image 437
danludwig Avatar asked Oct 28 '25 10:10

danludwig


1 Answers

As apsillers mentions, private static is probably what you want. While it's not supported in current builds, you will be able to have a private static member in TypeScript at some point in the future (the design team changed its mind on this one based on feedback similar to this).

like image 153
Ryan Cavanaugh Avatar answered Oct 29 '25 23:10

Ryan Cavanaugh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!