Vue2 + TypeScript
在 Vue2 + TypeScript 的项目中 遇到错误提示信息 returns the value of the first element in the array where predicate is true, and undefined otherwise
中文翻译为:返回数组中谓词为true的第一个元素的值,否则为 undefined
。
错误示例
interface IBoilerList {
boilerId: number
boilerName: string
label?: string
value?: number
}
interface ISteamerListItem {
steamerId: number
steamerName: string
value?: number
label?: string
}
export default class TestComponent extends Vue {
public searchValue: number | string = ''
public boilerList: IBoilerListItem[] = []
public steamerList: ISteamerListItem[] = []
/* 两个数组合二为一 */
get boilerListOrSteamerList() {
if (this.type === 'boiler') {
return this.boilerList
}
return this.steamerList
}
mounted(): void {
// list1 => [...]
// list2 => [...]
this.boilerList = list1.map((item: IBoilerListItem) => {
item.label = item.boilerName
item.value = item.boilerId
return item
})
this.stamerList = list2.map((item: ISteamerListItem) => {
item.label = item.steamerName
item.value = item.steamerId
return item
})
}
handleSearch(): void {
const searchItem = this.boilerListOrSteamerList.find((item: IBoilerListItem & ISteamerListItem) => item.value === this.searchValue)
// 此时的 find 函数提示:returns the value of the first element in the array where predicate is true, and undefined otherwise
console.log(searchItem?.label)
}
}
此时在 handleSearch 方法中的 find
函数会提示错误信息:returns the value of the first element in the array where predicate is true, and undefined otherwise
。
因为 IBoilerListItem
和 ISteamerListItem
有可能是 undefined
的可能性,所以 this.boilerList
和 this.steamerList
的值存在 [undefined]
的可能性,即 Array 中的第一个为真的元素可能是 undefined
。这就导致 find
函数可能得到的是一个 undefined
。
变通的写法
export default class TestComponents extends Vue {
// ...
handleSearch(): void {
const searchItem = (this.boilerListOrSteamerList as any).find((item: IBoilerListItem & ISteamerListItem) => item.value === this.searchValue)
console.log(searchItem?.label)
}
}