Typescript/Vue 3 -- 在对象数组中查找 () 值。对象的类型为 'unknown'
Typescript/Vue 3 -- find() value within an array of objects. Object is of type 'unknown'
如何解决以下打字稿错误?对于上下文,我使用 Vue 3 Composition API 最终使用结果来指定默认选项值是否应为 <option ... selected v-if="!isMatch">
.
Object is of type 'unknown'.
错误是突出显示第二个 'option'。
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 }
}
示例'Options'数据
[
{
"code": "CA",
"name": "Canada"
},
{
"code": "US",
"name": "United States"
}
]
.find()
returns 数组中的匹配对象,但您似乎只想要一个布尔值说明是否存在这样的对象,因此您应该改用 .some()
。
顺便说一句,你可以通过使用表达式而不是使用 return
:
来简化箭头函数
const isMatch = () => props.options.some(option => option['code'] === props.value)
经过一些重构,我通过 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 }
},
})
如何解决以下打字稿错误?对于上下文,我使用 Vue 3 Composition API 最终使用结果来指定默认选项值是否应为 <option ... selected v-if="!isMatch">
.
Object is of type 'unknown'.
错误是突出显示第二个 'option'。
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 }
}
示例'Options'数据
[
{
"code": "CA",
"name": "Canada"
},
{
"code": "US",
"name": "United States"
}
]
.find()
returns 数组中的匹配对象,但您似乎只想要一个布尔值说明是否存在这样的对象,因此您应该改用 .some()
。
顺便说一句,你可以通过使用表达式而不是使用 return
:
const isMatch = () => props.options.some(option => option['code'] === props.value)
经过一些重构,我通过 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 }
},
})