首页 > 解决方案 > VS Code Typescript 在 Vuejs 项目中给出错误“属性不存在”

问题描述

我在 Typescript 中有一个 Vuejs 项目。项目编译并运行完美,没有错误。但是 TS linter 是错误的。

我在单个组件文件中使用组件装饰器,如下所示:

//videocard.component.vue

<script lang="ts">
    import Vue from 'vue';
    import { Component, Prop } from 'vue-property-decorator';
    import { Video } from '../interfaces/video.interface';

    @Component
    export default class VideoCardComponent extends Vue {

        @Prop() readonly video: Video;
        @Prop() readonly loading: boolean;

        created(){
            console.log(this.static_url); // !COMPLAINS HERE!
        }

        get _video(){
            return this.video
        }

        get _loading(){
            return this.loading || false;
        }
    }
</script>

请注意我是如何尝试注销名为static_url. 这是有效的,因为在我的 app.ts 文件中,我将这个属性设置为:

//app.ts

Vue.prototype.static_url = (window as any).static_url;

我增加了类型,所以static_url是 Vue 上的一个属性。像这样:

// static_url.d.ts

import Vue from 'vue';

declare module 'vue/types/vue' {
    interface Vue {
      static_url: string;
    }

    interface VueConstructor {
      static_url: string
    }
}

Typescript linter 不会抱怨app.ts文件中的这个属性,但它会抱怨组件文件中的这个属性。为什么 Typescript 在组件文件中无法识别此属性?

为了完整起见,这是我的tsconfig.json文件:

{
    "compilerOptions": {
        "target": "es5",
        "lib": ["esnext", "dom"],
        "strict": true,
        "module": "es2015",
        "noImplicitAny": false,
        "moduleResolution": "node",
        "experimentalDecorators": true,
        "strictPropertyInitialization": false
    },
    "include": [
        "assets/js/video-app/src/**/*.ts",
        "assets/js/video-app/src/**/*.d.ts",
    ]
}

标签: typescriptvue.js

解决方案


我认为你是如此接近,我能找到的唯一问题是includetsconfig.json

您是否tsconfig.json放置在您的项目之外,所以您需要有assets/js/video-app/src路径?

通常,如果tsconfig.json在项目中,include应该如下所示。如果包含路径不正确,自定义类型定义将不起作用。

"include": [
   "src/**/*.ts"
]

你能检查一下是否也在目录static_url.d.tssrc

我做了一个 git repo 来模拟你的情况,你可以交叉检查你的设置。

Git 回购


推荐阅读