Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private static properties in TypeScript

Tags:

typescript

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?

like image 808
MuriloKunze Avatar asked Oct 10 '12 20:10

MuriloKunze


2 Answers

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!

like image 156
Brian Terlson Avatar answered Nov 04 '22 21:11

Brian Terlson


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.

like image 3
tony Avatar answered Nov 04 '22 22:11

tony