I am grappling with the concept of inheritance in typescript. I am facing an issue where I cannot seem to return the child type when invoking super within a method. Can someone shed light on why this example fails to return the child type? How does the use of as
impact it? Is there a workaround to achieve the desired behavior?
class Parent {
_value: number
constructor(value: number){
this._value = value
}
add(x: Parent): Parent {
return new Parent(x._value + this._value)
}
}
class Child extends Parent {
constructor(value: number) {
super(value)
}
add(x: Child): Child {
return super.add(x) as Child
}
}
let a = new Child(10)
let b = new Child(5)
let c = a.add(b)
console.log(a)
console.log(b)
console.log(c)
Output:
Child { _value: 10 }
Child { _value: 5 }
Parent { _value: 15 }