accessing static member from non-static function in typescript
Asked Answered
O

3

13

I am trying to access a static member from a non-static function in the class, and I get an error saying

Static member cannot be accessed off an instance variable

this is how my code looks -

class myClass {
  public static testStatic: number = 0;
  public increment(): void {
    this.testStatic++;
  }
}

From what I understand of static members/methods, we shouldn't access non-static members in static functions, but vice-versa should be possible. the static member is already created and is valid, so why can't I access from my non-static method?

Oballa answered 19/3, 2014 at 19:33 Comment(0)
P
17

Access static members from inside the class the same way you would from outside the class:

class myClass {
  public static testStatic: number = 0;
  public increment(): void {
    myClass.testStatic++;
  }
}
Poor answered 19/3, 2014 at 19:50 Comment(2)
It works but it's not a very good practice. Typescript should have a keyword for that. Something like static:: in php. The reason is you're duplicating the name of your class like this. Basically every instance should know its class, right?Ranzini
I don't see why it's needed for classes any more than it's needed for anything else. There isn't a keyword for the name of the enclosing function, the name of the enclosing module, etc.Poor
R
2

I personally prefer something in the spirit of:

class myClass{
    public static testStatic: number = 0;
    private class;

    constructor(){
        this.class = myClass;
    }

    public increment(): void {
        this.class.testStatic++;
    }
}

One cool thing is that typescript is actually allowing me to use 'class' as a variable.

Ranzini answered 25/3, 2015 at 11:59 Comment(1)
It is still duplication, but duplication in one place only - the constructor.Ranzini
F
1

For allowing inheritance you must use inside a instance method in order to don't repeat className:

<typeof ParentClass>this.constructor

See the Update section in this answer: https://mcmap.net/q/24628/-how-to-access-static-members-from-instance-methods-in-typescript

Fullmer answered 23/1, 2018 at 16:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.