代码之家  ›  专栏  ›  技术社区  ›  meallhour

试图在数组中查找值时出错

  •  0
  • meallhour  · 技术社区  · 5 年前

    我有一个数组 rowSelected 其中 two 元素。两者 elements TaskType 价值如下:

    第一个元素是 TaskType: First

    第二个因素是 TaskType: Second

    现在,如果有任何元素 任务类型:第一 然后我想做一个布尔变量 this.myflag true

    我在用 Array.find 详情如下:

    const rowSelected = this.selection.selected;
                if (rowSelected.find(x => x.TaskType.includes('ABC'))) {
                    this.myflag = true;
                }
    

    上面的代码给出了一个错误 Property 'TaskType' does not exist on type 'TInterface'.

    然而,当我 rowSelected.find(x => console.log(x.TaskType)) 我可以打印 type 价值

    这个 console.log(rowSelected) 他回来了

    0: {hostName: "ABC.COM",TaskType: "First", …}
    length: 1
    __proto__: Array(0)
    

    这个 TInterface 如下所示:

    export interface TInterface {
        objectId: string;
        hostName: string;
    }
    

    我不知道它为什么抱怨 色彩面 因为它与 rowSelected

    0 回复  |  直到 5 年前
        1
  •  0
  •   matthewjselby    5 年前

    我觉得你需要使用 instanceof 而不是 .type typeof .

    myflag = false
    class First {
        name: string
    }
    const first: First = new First(name: "first")
    class Second {
        name: string
    }
    const second: Second = new Second(name: "second")
    let rowSelected = [
        first,
      second
    ]
    rowSelected.forEach(x => { 
        if( x instanceof First ) {
            myflag = true;
        }
    })
    console.log(myflag)