0

I am using visual studio 2012 with TypeScript 1.0 and web essentials 3.7. I have declared some private static variables in my class in TypeScript file. But when I save this file, I do not see these members in JavaScript file and at the run time system throw exception.

Now

enter image description here

Earlier system use to generate these property. But recently I upgraded to TypeScript 1.0 & now I do not see these private static members.

Earlier: enter image description here

SharpCoder
  • 18,279
  • 43
  • 153
  • 249
  • The compiled JS seems valid to me. Why wouldn't you see them anymore? – Johannes Klauß Apr 15 '14 at 09:32
  • @JohannesKlauß: I have added two images. The first one does not have the private variables & throws error at the runtime while the second images shows the snapshot from a previous version (older version of typeScript). I am not sure why you said the compiled version looks valid to you. Aint it suppose to include private variable declaration? – SharpCoder Apr 15 '14 at 09:34

2 Answers2

2

It doesn't need to explicitly mention them in the compiled JavaScript because it is a dynamic language that allows the property to be added when they are first used, for example when you set the value...

Because the property is static, you should access it via the class name. In the example below, User._name.

class User {
    private static _name: string;

    static setName(name: string) {
        User._name = name;
    }

    static getName() {
        return User._name;
    }
}

User.setName('Steve');

alert(User.getName()); // 'Steve'

As I mentioned, there is no need to "set up" the fact that there will be a _name property because JavaScript doesn't require that. Here is the output from the above example:

var User = (function () {
    function User() {
    }
    User.setName = function (name) {
        User._name = name; // this adds a property if it doesn't exist
    };

    User.getName = function () {
        return User._name;
    };
    return User;
})();

User.setName('Steve');

alert(User.getName());

If you want it to appear, you need to assign a value at the outset:

private static _name = '';
Fenton
  • 241,084
  • 71
  • 387
  • 401
-1

There should not be any exception thrown, given you are accessing it correctly. Undefined members like

class A {
    private STATIC: string;
}

have a value of undefined which is consistent with normal Javascript:

var something; // undefined

Typescript previously initializing it to "" is actually "incorrect" (compared to similar languages). It certainly is nothing but Typescript guessing. If you want to retain this, you need to do

class A {
    private STATIC: string = "";
}
Ingo Bürk
  • 19,263
  • 6
  • 66
  • 100