returns the value of the first element in the array where predicate is true, and undefined otherwise

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
因为 IBoilerListItemISteamerListItem 有可能是 undefined 的可能性,所以 this.boilerListthis.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)
	}
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值