TS2339: Property does not exist on type 'CombinedVueInstance<Vue, unknown, ...>'的解决方案

Vue + TypeScript的项目里,在watch里使用data里定义的数据的时候,发现类型消失了,出现了这个报错:TS2339: Property does not exist on type 'CombinedVueInstance<Vue, unknown, unknown, unknown, Readonly<{ ... }>>'

查了一些资料之后,发现是因为computed没有显式声明返回类型。官方文档是这么说的:

因为 Vue 的声明文件天生就具有循环性,TypeScript 可能在推断某个方法的类型的时候存在困难。因此,你可能需要在 rendercomputed 里的方法上标注返回值。

const Component = Vue.extend({
  computed: {
    // 需要标注
    greeting(): string {
      return this.greet() + '!'
    }
  }
})

所以只需要在computed里的属性后面指明返回类型就好了。

其实仔细想想也很正常,因为没有显式声明类型的言下之意就是交给编译器进行推导,当computed里用到this的时候,如果想要知道computed的类型,就得知道this的类型,而如果想知道this的类型,又得知道computed的类型,就变成鸡生蛋蛋生鸡的问题了,所以需要显式声明类型来打破这个循环。显式声明类型之后,computed的类型就确定了,this的类型也就随之确定了。

发布了110 篇原创文章 · 获赞 132 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/HermitSun/article/details/104230253