flycran
flycran

Reputation: 13

Type inference of inherited classes

I have an inheritance class similar to the following

class A {
  clone(): A {
    return new A()
  }
  methodA() {
    return this.clone()
  }
}

class B extends  A {
  clone(): B{
    return new B()
  }
  methodB(): B {
    return this.clone()
  }
}
const a = new B

a.clone().methodA().methodB()

I hope that calling 'methoda' in B should return a cloned object of B. in fact, this is effective. However, type inference thinks that even calling 'methoda' in B will still return a, resulting in the last line of code

Upvotes: 0

Views: 85

Answers (1)

Matthieu Riegler
Matthieu Riegler

Reputation: 54579

In the light of this ticket, you won't be able to do what you want.

You cannot write a method that will return a new instance of whatever subclass you're calling from (new this()).

Upvotes: 1

Related Questions