如何使用 instanceof 确定对象的类型?

问题描述

我有一棵对象树,其节点可以是两种类型之一。类型(类)具有相同的结构。请告诉我如何检查节点类型?我在这里阅读了很多讨论。如果我理解正确,那么我需要“instanceof”。但它不起作用。

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 = "";
    }
}

使用“instaceof”的简单示例。第一级元素只有 ProductDirection 类型,第二级元素只有 ProductBrand 类型

enter image description here

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++;
        }
      }
    }

结果:a = b = 0

解决方法

问题很可能与您创建 productsTree 的方式有关,而不是与您确定元素类型的方式有关。您的检查器弹出窗口表明您的元素属于 Object 类型,因此您很可能将它们创建为非类型化对象,而不是类型化 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"},{ value: {id: 2,name: "brand_2"},children: null]
  ]}
]