javascript - Typescript/Vue 3——对象数组中的 find() 值。对象的类型为“未知”
问题描述
如何解决以下打字稿错误?对于上下文,我使用的是 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 }
},
})
推荐阅读
- haskell - Haskell 的惰性和列表理解。完成条件
- python - 用于多类分类的 ANN 模型
- c# - 与 python 请求相比,使用 myWebClient 将文件、mimetype 和文件名发送到 rest api
- elasticsearch - 我达到了弹性搜索的字段限制,但是当我查看 Kibana 时,似乎我还有很多字段空间
- node.js - 开发未捕获的异常:监听 EADDRINUSE:地址已在使用 :::5000
- react-native - 在不使用 Navigation SDK 的情况下获取与 Navigation SDK 相同的相机位置
- react-native - 如何使用 React Native 安排本地通知
- reactjs - 从对象渲染组件而不是无休止的比较
- php - (PHP) 从数据库呈现不同的数据类型
- javascript - 如何避免 useSelector hook 引起的组件更新