I have code like this:
interface Node{
value: number;
}
class Parent implements Node{
children: Node[] = [];
value: number = 0;
}
class Leaf implements Node{
value: number = 0;
}
function test(a:Node) : void {
if(a instanceof Leaf)
console.log("Leaf")
else
console.log("Parent")
}
Looking at https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#discriminated-unions, it seems like a different way of achieving this would be
type Parent = {kind: "Parent", value:number, children:(A|B)[]}
type Leaf = {kind: "Leaf", value:number}
type Node = Parent | Leaf
function test(a:Node) :void {
if(a.kind === "Leaf")
console.log("yes")
else
console.log("no")
}
Now, I'm confused as to what to use. All other languages I have used until now only had one of those options - here is typescript with both. Besides approach 1 having a constructor, while approach 2 is completely transpiled away, what are the real differences here? Which method is preferably seen in codebase?
The functionality, as you can see, is so that we can easily traverse a tree. Of course I could also just have only one type/class and set the children to [] there, but then the question of type vs class is repeated. And I was told that having different classes was more performance friendly.