尝试在数组中查找值时出现错误

时间:2020-09-16 16:38:09

标签: javascript node.js arrays typescript

我有一个数组rowSelected,其中包含two个元素。两个elements的值TaskType如下:

第一个元素具有TaskType: First

第二个元素有TaskType: Second

现在,如果任何元素具有TaskType: First,那么我想将布尔变量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;
}

我不确定为什么会抱怨TInterface,因为它与rowSelected根本无关

1 个答案:

答案 0 :(得分:0)

我认为您需要使用instanceof而不是.typetypeof

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)