VueJS 2 + TypeScript:计算值未检测到数据定义的 属性
VueJS 2 + TypeScript: computed value does not detect property defined by data
以下组件:
<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>
导致类型错误:
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
使用class风格的组件语法时不会出现这些错误,但我宁愿不要使用这样的语法。是否有推荐的方法来定义 VueJS 组件的类型?
Complete/minimal 存储库复制在这里:https://github.com/davidRoussov/vue-typescript-error
如 Vue 文档的 Typescript Support 部分所述:
在您的情况下,您应该将 bar: function() {
更改为 bar: function(): string {
如果您有一个 returns 值的 render() 方法,但没有 : VNode 注释,您可能会遇到同样的错误。
根据 docs:
Because of the circular nature of Vue’s declaration files, TypeScript may have difficulties inferring the types of certain methods. For this reason, you may need to annotate the return type on methods like render and those in computed.
因此,试试这个:
computed: {
bar: function(): string {
return this.foo;
}
}
以下组件:
<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>
导致类型错误:
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
使用class风格的组件语法时不会出现这些错误,但我宁愿不要使用这样的语法。是否有推荐的方法来定义 VueJS 组件的类型?
Complete/minimal 存储库复制在这里:https://github.com/davidRoussov/vue-typescript-error
如 Vue 文档的 Typescript Support 部分所述:
在您的情况下,您应该将 bar: function() {
更改为 bar: function(): string {
如果您有一个 returns 值的 render() 方法,但没有 : VNode 注释,您可能会遇到同样的错误。
根据 docs:
Because of the circular nature of Vue’s declaration files, TypeScript may have difficulties inferring the types of certain methods. For this reason, you may need to annotate the return type on methods like render and those in computed.
因此,试试这个:
computed: {
bar: function(): string {
return this.foo;
}
}