VueJS 2 + TypeScript:计算值未检测数据定义的属性

Dav*_*sov 5 javascript typescript vue.js vuejs2

以下组件:

<template lang="html">
  <div>
    <p>{{ bar }}</p>
  </div>
</template>

<script lang="ts">
import Vue from 'vue';

export const FooBar = Vue.extend({
  computed: {
    bar: function() {
      return this.foo;
    }
  },
  data: function() {
    return {
      foo: 'bar',
    };
  },
});

export default FooBar;
</script>
Run Code Online (Sandbox Code Playgroud)

导致类型错误:

13:19 Property 'foo' does not exist on type 'CombinedVueInstance<Vue, unknown, unknown, unknown, Readonly<Record<never, any>>>'.
    11 |   computed: {
    12 |     bar: function() {
  > 13 |       return this.foo;
       |                   ^
    14 |     }
    15 |   },
    16 |   data: function() {
Version: typescript 4.1.6
Run Code Online (Sandbox Code Playgroud)

使用类样式组件语法时不会发生此类错误,但我不想使用此类语法。是否有推荐的方法在 VueJS 组件上定义类型?

此处完整/最小存储库复制:https ://github.com/davidRoussov/vue-typescript-error

Ama*_*ckz 4

正如Vue 文档的Typescript 支持部分所述:

在你的情况下,你应该更改bar: function() {bar: function(): string {

如果您有一个返回值的 render() 方法,但没有 : VNode 注释,您可能会遇到相同的错误。