A
A
alex4answ2020-10-26 12:35:39
typescript
alex4answ, 2020-10-26 12:35:39

Why is the type of the child class not compatible with the parent, can't be assigned this?

Good afternoon, I still could not figure out the polymorphic this and why child classes are incompatible with parent classes at some points:

class A {
  parent: A;

  constructor(parent: A) {
    this.parent = parent;
  }
}

class B extends A {
  getParent(): this { // ERROR
    return this.parent; // ERROR
  }
}

Error: Type 'A' is not assignable to type 'this'. 'this' could be instantiated with an arbitrary type which could be unrelated to 'A'.

Yes, we are talking about the impossibility to assign a type to a Apolymorphic type this

Why?, because subclass B extends class A, so they are compatible, what's the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex, 2020-10-26
@alex4answ

That's just the point, that it expands it .
Class B = A, but A != B.
You say that the method should return class B (with all extensions) but you return A where there are none.
working version

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question