Typescript: Proposal: simplify access to static members

Created on 13 Jul 2015  路  6Comments  路  Source: microsoft/TypeScript

When accessing static member of class you must write class name followed with dot before member name. But this is redundant when using that member inside the class itself.
Let's see an example (it's a little bit far-fetched but shows the case):

class SampleClassWithLongName {
    static SCALE = 5;
    private num:number;

    // ...

    getScaled():number {
        return SampleClassWithLongName.scaleNumber(this.num);
    }

    static scaleNumber(n:number):number {
        return n * SampleClassWithLongName.SCALE;
    }
}

My suggestion is to extend the functionality of static keyword (just to not introduce a new one) so it will help eliminate the need to continuously repeat class name.
With this feature our example became shorter and more readable:

class SampleClassWithLongName {
    static SCALE = 5;
    private num:number;

    // ...

    getScaled():number {
        return static.scaleNumber(this.num);
    }

    static scaleNumber(n:number):number {
        return n * static.SCALE;
    }
}
Declined Needs Proposal Suggestion

Most helpful comment

mhegazy, accessing static property via class is not the same as accesing via 'this'.
If you access

class Parent {
  static x: 0;
  public method(): number {  
    return Parent.x;
  }
}

all child classes (Child extends Parent) will use x = 0 even if they redefined it.
So accessing by 'this' is very useful, please give a chance to 'this.x' syntax.

All 6 comments

+1

or

this::staticValue

this.constructor.scaleNumber will work on methods while not on static functions.

+1

The class name does not seem like that bad of an option, and does not justify the complexity of adding a new syntax to the language.

mhegazy, accessing static property via class is not the same as accesing via 'this'.
If you access

class Parent {
  static x: 0;
  public method(): number {  
    return Parent.x;
  }
}

all child classes (Child extends Parent) will use x = 0 even if they redefined it.
So accessing by 'this' is very useful, please give a chance to 'this.x' syntax.

How hard would it be to user super as a reference to the super class?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

weswigham picture weswigham  路  3Comments

Roam-Cooper picture Roam-Cooper  路  3Comments

jbondc picture jbondc  路  3Comments

wmaurer picture wmaurer  路  3Comments

seanzer picture seanzer  路  3Comments