首页 > 解决方案 > 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"
    }
]

标签: javascripttypescriptvue.jsvuejs3vue-composition-api

解决方案


经过一些重构,我通过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 }
    },
})

推荐阅读