Currently, I am working on creating a binary tree that is strictly type-safe. Here's my progress so far:
class BinaryNode<N extends BinaryNode<N>> {
constructor(left?: N, right?: N) {}
}
class A extends BinaryNode<A> { }
class B extends BinaryNode<B> { }
const leafA = new A();
const leafB = new B();
const rootA = new A(leafA, leafB);
One problem I have encountered is that the code compiles without any errors. However, I believe it should not compile because the A constructor should only accept two or fewer instances of class A, and nothing else.
My main question is: How can I achieve this level of type-safety? My goal is to create a homogeneous tree structure consisting solely of instances of class A, enforced by the compiler.