程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Typescript/Vue 3——对象数组中的 find() 值。对象的类型为“未知”大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决Typescript/Vue 3——对象数组中的 find() 值。对象的类型为“未知”?

开发过程中遇到Typescript/Vue 3——对象数组中的 find() 值。对象的类型为“未知”的问题如何解决?下面主要结合日常开发的经验,给出你关于Typescript/Vue 3——对象数组中的 find() 值。对象的类型为“未知”的解决方法建议,希望对你解决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"
    }
]

解决方法

.find() 从数组中返回一个匹配的对象,但您似乎只想要一个布尔值来说明这样的对象是否存在,因此您应该使用 .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,SELEctions: {
            required: true,type: Array as PropType<Options>
        }
        modelValue: {
            required: true,setup(props) {
        const ismatch = () =>
            props.SELEctions.some(
                SELEction => SELEction['code'] === props.modelValue
            )

        return { ismatch }
    },})

大佬总结

以上是大佬教程为你收集整理的Typescript/Vue 3——对象数组中的 find() 值。对象的类型为“未知”全部内容,希望文章能够帮你解决Typescript/Vue 3——对象数组中的 find() 值。对象的类型为“未知”所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。