ojosilva
ojosilva

Reputation: 2094

Why static member cannot be accessed in a property method but ok in prototype method?

Can someone help me understand why is it an error to access a static member from a property method an in Typescript? It works ok in plain ES6 and as a proper prototype method.

class FooBar {
    static v = 123;

    static foo = () => this.v;  // this is an error in TS (but ok in ES6)

    static bar() {
        return this.v;  // but this is ok in TS??
    }
}

This is the error, it seems to consider the code in the function body as the property initializer itself:

apptest2.ts:40:24 - error TS2334: 'this' cannot be referenced in a static property initializer.

40     static foo = () => this.v;
                          ~~~~

The error would make sense if the code was more like static foo = this.v, but being part of the function callback does not make sense to consider this as part of the initialization phase of the class, where this could not be defined... anyway, that also works in ES6 which adds to my confusion on why this is an error and why it works in bar() but not in foo().

Upvotes: 5

Views: 2001

Answers (1)

edzillion
edzillion

Reputation: 3661

I had this issue come up today and I noticed the following:

if you are using arrow functions you need to reference the ClassName rather than this

class FooBar {
    static v = 123;
    static fooArrow = () => FooBar.v; //works
    static foo () {this.v}; //works
}

It seems this is a known issue in Typescript, and there have been long term discussions on a possible fix. I think it's a good idea to steer clear of arrow functions in Classes for the moment due to issues around how the this context is bound.

Upvotes: 7

Related Questions