I am working with a class structure.
class Node {
children: Node[];
}
This class is inherited by various other classes.
class Block extends Node {
// ...
}
In each of the inherited classes, I want to include a function named replaceChild:
const block = new Block();
block.replaceChild(oldChild, newChild);
Instead of implementing this function in every inherited class, I would like to keep my classes immutable. This means when replacing a child, I want to create a new instance with the updated children
. However, I want the replaceChild
method defined in the Node
class to return an instance of the specific inherited class rather than just a generic Node
:
class Node {
children: Node[];
replaceChild(oldChild, newChild): Node {
// ...
return new Node(/* ... */)
}
}
class Block extends Node {
// ...
}
const block = new Block();
const newMutatedBlock: Block = block.replaceChild(oldChild, newChild);
I am using TypeScript
. How can I instruct TypeScript, without having to typecast each time, that the replaceChild
method on a Block
node should return a Block
instance instead of a Node
?