As I work on creating a generic parent class to handle multiple children, I have encountered a challenge. My goal is to define an abstract function in the parent class that will take in a child object and return that same class. Here's my initial attempt:
abstract class Parent<T> {
constructor(public readonly val: T) { }
public abstract add<C extends Parent<T>>(other: C): C;
}
Next, let's look at how this concept translates into a child class. In this example, the child class extends Parent<string>
, working with a Child
object input and output.
class Child extends Parent<string> {
public add(other: Child): Child {
return new Child(this.val + other.val);
}
}
However, an error occurs at the add
line:
Property 'add' in type 'Child' is not assignable to the same property in base type 'Parent<string>'.
Type '(other: Child) => Child' is not assignable to type '<C extends Parent<string>>(other: C) => C'.
Type 'Child' is not assignable to type 'C'.
'C' could be instantiated with an arbitrary type which could be unrelated to 'Child'.ts(2416)
This error message is perplexing. Despite explicitly extending Parent<string>
, the issue persists. Adding a type to the function signature does not resolve it either:
class Child extends Parent<string> {
public add<Child>(other: Child): Child {
return new Child(this.val + other.val);
}
}
The error now appears on the return
line:
Type 'Child' is not assignable to type 'Child'. Two different types with this name exist, but they are unrelated.
'Child' could be instantiated with an arbitrary type which could be unrelated to 'Child'.ts(2719)
If anyone can provide insight into why these errors are occurring and their implications, I would greatly appreciate it.
A temporary solution is to remove the abstract function from Parent
. However, I am seeking a more permanent resolution. Are there alternative strategies I should consider?
abstract class Parent<T> {
constructor(public readonly val: T) { }
}