programing

형식 스크립트가 있는 Vue2, 유형에 속성이 없습니다.

prostudy 2022. 8. 30. 21:41
반응형

형식 스크립트가 있는 Vue2, 유형에 속성이 없습니다.

다음 Vue 컴포넌트가 있습니다.

<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가 컴파일되면 다음 오류가 나타납니다.

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 |     });

제가 이 문제를 어떻게 해결할 수 있는지, 또는 왜 이런 일이 일어나는지 설명해 줄 수 있는 사람 있나요?

뭐, 좋은 답은 없지만, 이론은 있어요.

원래 유형 선언은 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

내 생각에 당신의 객체 선언이 없다면 typescript는 다음과 같이 생각할 것이다.dataDefaultData<V> = object그러나 일단 오브젝트를 반환한다고 하면 데이터가 갑자기 일치합니다.((this: V) => object)대신.이제 예상 타이프스크립트this종류로 되어 있다V(vue-instance라고 생각됩니다) vue 인스턴스의 정의에는 스낵바가 없기 때문에 boom, typscript srow.

많은 추측이 있지만, 분명히 돌아온 것 말고는 거의 모든 것이object에 있는 두 번째 시그니처와 일치하지 않도록 합니다.DefaultData<V>.

언급URL : https://stackoverflow.com/questions/50810291/vue2-with-typescript-property-does-not-exist-on-type

반응형