I have created a class that utilizes the visitor design pattern:
abstract class MyNode {};
class MyNodeA extends MyNode {};
class MyNodeB extends MyNode {};
abstract class NodeVisitor {
abstract visitMyNodeA(node: MyNodeA): unknown;
abstract visitMyNodeB(node: MyNodeB): unknown;
public visit(node: MyNode) {
if(node instanceof MyNodeA) {
return this.visitMyNodeA(node);
} else if(node instanceof MyNodeB) {
return this.visitMyNodeB(node);
} else {
throw new Error('Unknown node type on visitor');
}
}
}
In my implementation of NodeVisitor
, I would like to define custom return types for each visit function.
class MyNodeVisitor extends NodeVisitor {
visitMyNodeA(node: MyNodeA): number {
return 1;
}
visitMyNodeB(node: MyNodeB): number {
return this.visit(new MyNodeA()) + 1;
}
}
However, there is an error being generated by the TypeScript compiler. It does not recognize that calling visit
with a parameter of type MyNodeA
should redirect to the visitMyNodeA
function, which now returns a number
.
What steps can I take to successfully implement this solution?