带有打字稿的 Vue2,类型上不存在属性 [英] Vue2 with typescript, Property does not exist on type
问题描述
我有以下 Vue 组件:
I have the below Vue component:
<template>
<v-snackbar bottom :color="color" v-model="snackbar">
{{ msg }}
<v-btn flat @click.native="close()">Close</v-btn>
</v-snackbar>
</template>
<script lang="ts">
import Vue from 'vue';
import VueEvent from '../../VueEvent';
export default Vue.extend({
data(): object {
return {
snackbar: false,
msg: '',
color: '',
};
},
created() {
VueEvent.listen('snackbar', (data) => {
this.snackbar = true;
this.msg = data.msg;
this.color = data.color;
});
this.malert();
},
methods: {
close(): void {
this.snackbar = false;
}
}
});
</script>
<style scoped>
</style>
Typescript 编译时出现以下错误:
When Typescript compiles I get the following error:
Property 'snackbar' does not exist on type 'CombinedVueInstance<Vue, object, { close(): void; }, {}, Readonly<Record<never, any>>>'.
28 | methods: {
29 | close(): void {
> 30 | this.snackbar = false;
| ^
31 | }
32 | }
33 | });
有谁知道我如何解决这个问题,或者解释它为什么会发生?
Does anyone know how I can solve this problem, or explain why its happening?
推荐答案
好吧,我没有很好的答案给你,但我有理论:
Well, I don't have a good answer for you, but I have theory:
原始类型声明位于 vue/types/options.d.ts:
The original type declaration resides in vue/types/options.d.ts:
type DefaultData<V> = object | ((this: V) => object); // here is the kicker
Data=DefaultData<V>
data?: Data;
我发现:
data():object { ... // this.snackbar does not exist
data(){ ... // this.snackbar does exist.
data(): any { ... // this.snackbar does exist.
data(): { snackbar: boolean; msg: string; color: string } { ... // Also valid
我认为没有你的对象声明打字稿会认为 data
是 DefaultData
.但是一旦你说它返回一个对象,数据会突然匹配 ((this: V) => object)
.现在打字稿期望 this
是 V
类型(我假设它是一个 vue 实例)并且因为该 vue 实例在它的定义中没有小吃栏,boom,打字稿抛出.
I think without your object declaration typescript will think that data
is DefaultData<V> = object
. But once you say it returns an object, data will suddenly match ((this: V) => object)
instead. Now typescript expects this
to be of type V
(which I assume is a vue-instance) and since that vue instance does not have a snackbar in it's definition, boom, typescript throws.
这里有很多猜测,但我认为几乎任何除了显式返回 object
都会与 DefaultData
Lot's of guessing here, but I think pretty much anything except explicitly returning object
would work to not match that second signature in DefaultData<V>
.
这篇关于带有打字稿的 Vue2,类型上不存在属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!