Why is it an issue to access a static member from a property method in TypeScript? This behavior works fine in plain ES6 and as a proper prototype method.
class FooBar {
static v = 123;
static foo = () => this.v; // this throws an error in TS (but works in ES6)
static bar() {
return this.v; // but this is allowed in TS??
}
}
The error arises because the code in the function body is considered part of the property initializer itself:
apptest2.ts:40:24 - error TS2334: 'this' cannot be referenced in a static property initializer.
40 static foo = () => this.v;
~~~~
This error would make more sense if the code was like static foo = this.v
, but being within a function callback makes it confusing why it's considered part of the initialization phase of the class where this
might not be defined. However, this same structure works in ES6 which adds to the confusion as to why it's an error in TypeScript and why it works in bar()
but not in foo()
.