Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong this in inherited static class method

Tags:

typescript

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?

like image 560
Estus Flask Avatar asked Mar 09 '26 22:03

Estus Flask


1 Answers

It's a known issue, current workaround is

class Foo {
  static classFoo<T extends Foo>(this: { new (): T } & typeof Foo): T {
    return new this();
  }
}
like image 71
artem Avatar answered Mar 12 '26 13:03

artem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!