【问题标题】:Vue 3 PropType doesn't see the interfaceVue 3 PropType 看不到界面
【发布时间】:2021-08-16 09:30:19
【问题描述】:

我使用 onMonted 钩子创建父组件 Product vue:

setup () {
    let data = reactive({
      product: {},
      productInfo: {},
      loaded: false,
      shippingDate: ''
    })

    onMounted(async () => {
      const product = await findProduct()
      data.productInfo = productInfo(product)
      data.product = product
      data.loaded = true
    })

    return { data }
  },

子组件ProductAttributes

props: {
    product: {
      type: Object as PropType<Product>,
      required: true
    }
  },
  setup (props) {
    const configurableOptions = ref([])
    const configurableChildren = ref([])

    onMounted(() => {
      configurableChildren.value = props.product.configurable_children
      //@ts-ignore
      configurableOptions.value = props.product.configurable_options.map((option: ConfigurableOptions) => {
        option.values = option.values.sort((a: ConfigurableOptionsValue, b: ConfigurableOptionsValue) => {
          return parseInt(a.value_index) - parseInt(b.value_index)
        })
        return option
      })

      // resetAttrs()
    })

    return {
      configurableChildren,
      configurableOptions
    }
  }

但在这种情况下,typescript 向我显示错误Property 'configurable_children' does not exist on type 'unknown'.但如果我将 setup function props 更改为 setup (props: { product: Product }) { 并将 props 更改为props: ['product'] typescript 将停止显示错误。

为什么会这样?为什么 typescript 不从 PropType 中提取类型?

PS 我用的是defineComponent

【问题讨论】:

  • 你用的是哪个版本的vue?你能在一个虚拟组件中重现这个吗?我只是出于好奇尝试了我的一个组件,但没有遇到同样的问题。
  • 一个unknown 属性通常表示props 声明中的一个问题,甚至是与当前错误无关的属性。你能显示props选项的完整声明吗?

标签: typescript vue.js vuejs3


【解决方案1】:

对于在这种情况下遇到错误 Property 'x' does not exist on type 'unknown' 的其他人,我可以通过将我的 typescript 版本从 4.1.5 升级到 4.5.5 来解决它。

【讨论】:

  • nop...这个问题仍然存在!
【解决方案2】:

@Max Stevens 是一位救世主。我被困在 Vue 3 中,打字稿解决了Property 'x' does not exist on type 'unknown',所以每次我传递属性时,我都会在子组件中这样做:

家长:

<some-component :b-prop="{known object 'B' with CustomInterface goes here}">

孩子:

props: {
  bProp: Object as PropType<CustomInterface>,
  required: true
},
data () {
  return {
    b: this.bProp as CustomInterface
  }
},
created () {
  console.warn(b.customProperty) // no more errors of unknown
}

这绝对很烦人,因为每个属性都需要在数据中进行这种额外的“包装”。

更新到 4.5.5 后问题消失了。现在它只是 b: Object as PropType&lt;CustomInterface&gt; 没有 bPropdata wrapper 伟大的!谢谢!

【讨论】:

    猜你喜欢
    • 2018-10-26
    • 2021-11-05
    • 2019-05-07
    • 1970-01-01
    • 2015-06-18
    • 2014-07-12
    • 1970-01-01
    • 2021-03-20
    • 2020-06-25
    相关资源
    最近更新 更多