Estus Flask
Estus Flask

Reputation: 222935

Wrong this in inherited static class method

The question refers to TypeScript typing issue.

This piece of code

class Foo {
  static classFoo() {
    return new this();
  }
}

class Bar extends Foo {
  instanceBar() {}
}


Bar.classFoo().instanceBar();

results in error:

Property 'instanceBar' does not exist on type 'Foo'

Of course, this isn't true because this === Bar when Bar.classFoo() is called. With type errors being ignored, code works as expected, due to how inheritance works in ES6 classes.

Why does this happen? Is it a known bug? How can this be fixed?

Upvotes: 3

Views: 65

Answers (1)

artem
artem

Reputation: 51719

It's a known issue, current workaround is

class Foo {
  static classFoo<T extends Foo>(this: { new (): T } & typeof Foo): T {
    return new this();
  }
}

Upvotes: 2

Related Questions