【问题标题】:Typescript/Vue 3 -- find() value within an array of objects. Object is of type 'unknown'Typescript/Vue 3——对象数组中的 find() 值。对象的类型为“未知”
【发布时间】:2021-09-18 16:18:07
【问题描述】:

如何解决以下打字稿错误?对于上下文,我使用的是 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"
    }
]

【问题讨论】:

  • 您能分享一下props 设置部分吗?从您在模板上的使用方式来看,我认为 RoToRa 是正确的,您可能想要使用 Array.prototype.some 而不是 find。此处需要更多上下文。
  • @YomT。添加了道具。
  • computed 用于isMatch
  • @Lynx 谢谢,但不幸的是收到了同样的错误。

标签: javascript typescript vue.js vuejs3 vue-composition-api


【解决方案1】:

.find() 从数组中返回一个匹配的对象,但您似乎只需要一个布尔值来说明这样的对象是否存在,因此您应该改用.some()

顺便说一句,您可以通过仅使用表达式而不是使用return 来简化箭头函数:

const isMatch = () => props.options.some(option => option['code'] === props.value)

【讨论】:

  • 谢谢,虽然我仍然需要解决“对象属于‘未知’类型”错误。
  • 对不起,我认为这会有所帮助。我没有任何其他想法。
【解决方案2】:

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

【讨论】:

  • 是的,这是一个常见的问题。
猜你喜欢
  • 2021-06-19
  • 2020-08-23
  • 2021-04-12
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多