如何解决以下打字稿错误?对于上下文,我使用的是 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"
}
]
答案 0 :(得分:1)
.find()
从数组中返回一个匹配的对象,但您似乎只想要一个布尔值来说明这样的对象是否存在,因此您应该使用 .some()
代替。
顺便说一句,您可以通过仅使用表达式而不是使用 return
来简化箭头函数:
const isMatch = () => props.options.some(option => option['code'] === props.value)
答案 1 :(得分:1)
经过一些重构后,我通过 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 }
},
})