Vue+TS/Typescript:Property does not exist on type ‘(() => any) | ComputedOptions<any>‘

问题描述

源代码如下

interface IMenuButton {
    
    
  top: number // 上边界坐标,单位:px
  right: number // 右边界坐标,单位:px
  bottom: number // 下边界坐标,单位:px
  left: number // 左边界坐标,单位:px
}

export default Vue.extend({
    
    
  props: {
    
    
    menuButton: {
    
    
      type: Object as PropType<IMenuButton>,
    },
  },

  computed: {
    
    
    styleString() {
    
    
      if (this.menuButton) {
    
    
        return `padding-top: ${
      
      this.menuButton.top}px;`
      } else {
    
    
        return 'padding-top: 50px;'
      }
    },
  }
})

打包的时候报错

TS2339: Property 'top' does not exist on type '(() => any) | ComputedOptions<any>'.
  Property 'top' does not exist on type '() => any'.
    41 |     styleString() {
    
    
    42 |       if (this.menuButton) {
    
    
  > 43 |         return `padding-top: ${
      
      this.menuButton.top}px;`
       |                                                ^^^
    44 |       } else {
    
    
    45 |         return ''
    46 |       }

明明声明了menuButton对象的类型,也判断了为null的情况,还是提示属性top不存在

解决方案

在计算属性的返回值上加上类型注解,很奇怪的解决方式

  computed: {
    
    
    styleString(): string {
    
    
      if (this.menuButton) {
    
    
        return `padding-top: ${
      
      this.menuButton.top}px;`
      } else {
    
    
        return 'padding-top: 50px;'
      }
    },
  }

参考

猜你喜欢

转载自blog.csdn.net/mouday/article/details/129637169