I am facing a scenario where I have a parent class that mandates child classes to implement a unique businesslogic()
method. Each child class has its own version of the businesslogic()
method with different type signatures.
The parent class includes a common method that relies on the implementation of the child's businesslogic()
method.
This code snippet illustrates the situation:
abstract class Parent {
protected name: string;
constructor(name: string) {
this.name = name;
}
protected abstract businesslogic(params?: unknown): unknown;
public setup(params?: unknown): unknown {
// code logic involving `params`
const result = this.businesslogic(params);
// process the outcome of the business logic
console.log(result);
// return the result
return result;
}
}
class Child1 extends Parent {
businesslogic(c: number): number {
return c + 1;
}
}
class Child2 extends Parent {
businesslogic(c: string): string {
return c;
}
}
const firstChild = new Child1("Mirco");
firstChild.setup(1);
const secondChild = new Child2("Isolde");
secondChild.setup("a");
In this instance, each child class defines a custom businesslogic()
method with varying type signatures.
When using tsc
, it seems to interpret firstChild.setup(1)
based on the general signature
Parent.setup(params?: unknown): unknown
-- which functions correctly. However, I am seeking an improved approach where I can somehow "override" the type signature of setup(params?: unknown): unknown
within the child class declaration to enforce stricter type constraints when invoking a child's setup()
method.
Essentially, I aim to modify the type signature of the common method in the parent class within the child class declaration. Is there a way to achieve this?
I welcome suggestions for more elegant solutions to tackle this issue!