Typescript/Vue 3 -- 对象数组中的 find() 值。对象类型为 'unknown'



如何解决以下类型脚本错误?就上下文而言,我使用Vue 3 Composition API,最终使用结果来指定默认选项值是否应为<option ... selected v-if="!isMatch">

Object is of type 'unknown'.

错误是突出显示第二个"选项"。

props:{
value: {
required: true,
type: String,
},
options: {
required: true,
type: Array,
},
}
setup(props){
const isMatch = () => props.options.find(option => {
return option['code'] === props.value
})
return { isMatch }
}

示例"选项"数据

[
{
"code": "CA",
"name": "Canada"
},
{
"code": "US",
"name": "United States"
}
]

经过一点重构,我通过Vue Docs找到了这个。我需要添加两个接口定义和PropType导入。

import { defineComponent, PropType } from 'vue'
interface Option {
code: String,
name: String
}
interface Options extends Array<Option>{}
export default defineComponent({
props: {
id: {
required: true,
type: String,
},
title: {
required: true,
type: String,
},
selections: {
required: true,
type: Array as PropType<Options>
}
modelValue: {
required: true,
type: String,
},
},
setup(props) {
const isMatch = () =>
props.selections.some(
selection => selection['code'] === props.modelValue
)
return { isMatch }
},
})

.find()从数组中返回一个匹配的对象,但您似乎只想要一个布尔值来说明是否存在这样的对象,因此应该使用.some()

顺便说一句,你可以通过使用一个表达式而不是使用return:来简化箭头函数

const isMatch = () => props.options.some(option => option['code'] === props.value)

最新更新