This is wrong in an inherited static class

The question is related to a TypeScript input issue.

This piece of code

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

class Bar extends Foo {
  instanceBar() {}
}


Bar.classFoo().instanceBar();

      

results in an error:

The instanceBar property does not exist on type 'Foo'

Of course it is not, because when this === Bar

you call Bar.classFoo()

. By ignoring type errors, the code works as expected because of the way inheritance works in ES6 classes.

Why is this happening? Is this a known bug? How can this be fixed?

+3


source to share


1 answer


This is a known issue , current workaround



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

      

+2


source







All Articles