I have a tree of objects whose node can be one of two types. The types (classes) have the same structure. Please tell me how can I check the node type? I've read a lot of discussions here. If I understand correctly, then I need "instanceof". But it doesn't work.
export class ProductTree {
public value: ProductDirection | ProductBrand | null;
public children: ProductTree[];
}
export class ProductDirection {
public id: number;
public name: string;
constructor() {
this.id = 0;
this.name = '';
}
}
export class ProductBrand{
public id: number;
public name: string;
constructor() {
this.id = 0;
this.name = "";
}
}
Simple example of using "instaceof". Elements at the first level are only of type ProductDirection, second level are only of type ProductBrand
var a = 0;
var b = 0;
for (let val of this.productsTree) {
if (val.value instanceof ProductDirection) {
a++;
}
for (let val1 of val.children) {
if (val1.value instanceof ProductBrand) {
b++;
}
}
}
Result: a = b = 0
The issue is most likely with how you created your productsTree
and not with how you determine the element type. Your inspector popup suggests that your elements are of type Object, so you most likely created them as non-typed objects instead of typed ProductTree/ProductDirection/ProductBrand:
// For that data your instanceof should work
let v: ProductTree[] = [
{ value: new ProductDirection, children: [
{ value: new ProductBrand(), children: null],
{ value: new ProductBrand(), children: null]
]}
]
// For that data your instanceof shouldn't work
let v = [
{ value: {id: 1, name: "direction_1"}, children: [
{ value: {id: 2, name: "brand_1"}, children: null],
{ value: {id: 2, name: "brand_2"}, children: null]
]}
]