Reputation: 15563
If I do something like this below, how can I access the property out the class?
class Person
{
private static name: string;
}
console.log(Person.name);
Shouldn't it inaccessible?
Upvotes: 31
Views: 37443
Reputation: 10045
Well, not really, in fact you can. Maybe most important is to ask about the TypeScript version it relates. I have v1.5 beta, part of my VS2012 installation (yes, it works despite it is targeted at VS2013).
I have a class like this:
class ItemListPreProcessor {
private static names: string[] = [ 'Name', 'Age' ];
static createHeader = (eltName: string) => {
var pdiv = $(eltName);
pdiv.html('<table><thead><tr></tr></thead></tr><tbody></tbody></table>');
var row = $('tr', pdiv);
ItemListPreProcessor.names.forEach((n) => {
row.append('<th>' + n + '</th>');
});
return $('tbody', pdiv);
};
}
In the sample above you can see both private
and static
. The class is compiled to the following JavaScript:
var ItemListPreProcessor = (function () {
function ItemListPreProcessor() {
}
ItemListPreProcessor.names = ['Name', 'Age'];
ItemListPreProcessor.createHeader = function (eltName) {
var pdiv = $(eltName);
pdiv.html('<table><thead><tr></tr></thead></tr><tbody></tbody></table>');
var row = $('tr', pdiv);
ItemListPreProcessor.names.forEach(function (n) {
row.append('<th>' + n + '</th>');
});
return $('tbody', pdiv);
};
return ItemListPreProcessor;
})();
and there's no problem with either compiling it (this you see), as well as executing it (this you should trust, or, if you like, try).
Upvotes: 1
Reputation: 887
class Person
{
private static theName: string = "John";
static get name():string{
return Person.theName;
}
}
console.log(Person.name);
If a static property is private we need to provide a static get method to access it. This may not be a common solution but it is the only way I know of to directly access a private static property. On the other hand, you may have to add a second get method if you also intend to access the property from an instantiated object. Both get methods can have the same name since the static get method will be invisible to the instantiated object.
Upvotes: 6
Reputation: 9630
It should be an error but isn't. From the spec, section 8.2.1:
It is not possible to specify the accessibility of statics—they are effectively always public.
Accessibility modifiers on statics are something the team has considered in the past. If you have a strong use case you should bring this up on codeplex site!
Upvotes: 28