【问题标题】:Property doesn't exist属性不存在
【发布时间】:2022-01-05 15:21:34
【问题描述】:

好吧可能是一个简单的,但这让我很困惑

我有一个使用定义的 SFC

export default defineComponent({
    setup(): { args: Args; preview: Point[] } {
        const args = new Args();
        const preview: Point[] = [];
        args.values.push(...args.shape.shapeArgs.map((d) => d.default));
        return { args, preview: preview };
    },
    computed: {
        previewSize() {
            return {
                width: (Math.max(1, ...this.preview.map((p) => p.x)) + 40) * 10,
                height: (Math.max(1, ...this.preview.map((p) => p.y)) + 40) * 10,
            };
        },
...

但是它不会运行,因为

TS2339: Property 'preview' does not exist on type 'ComponentPublicInstance<{} | {}, {}, {}, {}, {}, EmitsOptions, {} | {}, {}, false, ComponentOptionsBase<{} | {}, {}, {}, {}, {}, ComponentOptionsMixin, ComponentOptionsMixin, EmitsOptions, string, {}>>'.
  Property 'preview' does not exist on type '{ $: ComponentInternalInstance; $data: {}; $props: {} | {}; $attrs: Record<string, unknown>; $refs: Record<string, unknown>; $slots: Readonly<InternalSlots>; ... 7 more ...; $watch(source: string | Function, cb: Function, options?: WatchOptions<...> | undefined): WatchStopHandle; } & ... 4 more ... & ComponentCustom...'.
    56 |        previewSize() {
    57 |            return {
  > 58 |                width: (Math.max(1, ...this.preview.map((p) => p.x)) + 40) * 10,
       |                                            ^^^^^^^                          

由于明确定义了预览,我对它为什么不存在感到困惑

【问题讨论】:

  • 这很有趣,因为实际上我发现的每个示例都使用类型推断来进行打字,而没有任何明确的内容,因此它显然应该能够捡起它
  • 感谢@Francesco Vattiato,看来我的思路已经交叉,并且以不应该混合的方式将选项和构图混合在一起

标签: javascript typescript vue.js


【解决方案1】:

这是来自Vue3 typescript documentation about computed

import { defineComponent, ref, computed } from 'vue'

export default defineComponent({
  name: 'CounterButton',
  setup() {
    let count = ref(0)

    // read-only
    const doubleCount = computed(() => count.value * 2)

    const result = doubleCount.value.split('') // => Property 'split' does not exist on type 'number'
  }
})

您可以尝试执行以下操作:

export default defineComponent({
    setup(): { args: Args; preview: Point[] } {
        const args = new Args();
        const preview: Point[] = [];
        args.values.push(...args.shape.shapeArgs.map((d) => d.default));
        const previewSize = computed(() => ({
                width: (Math.max(1, ...this.preview.map((p) => p.x)) + 
                40) * 10,
                height: (Math.max(1, ...this.preview.map((p) => p.y)) + 
                40) * 10,
            }))
        return { args, preview: preview, previewSize: previewSize };
    }
...

【讨论】:

  • 谢谢你好像明白了
  • 供其他人参考,计算参数是选项 API 的一部分,设置函数是组合 API 的一部分,因为它们是制作组件的不同方式,它们并不总是有效尤其是当 typescript 包含在组合中时
猜你喜欢
  • 2019-05-04
  • 2013-10-10
  • 2020-12-31
  • 1970-01-01
  • 2021-09-04
  • 2020-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多