【问题标题】:VS Code Typescript gives error "property does not exists" in Vuejs ProjectVS Code Typescript 在 Vuejs 项目中给出错误“属性不存在”
【发布时间】:2021-08-03 07:35:28
【问题描述】:

我在 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",
    ]
}

【问题讨论】:

    标签: typescript vue.js


    【解决方案1】:

    我觉得你很亲密,我能找到的唯一问题是tsconfig.json中的include

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

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

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

    您能否检查static_url.d.ts 是否也在src 目录中。

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

    Git Repo

    【讨论】:

      【解决方案2】:

      如果在这种情况下类型准确性不重要,您可以这样做:

      (this as any).static_url
      

      如果类型准确性是一个问题,那么我的 2 美分就是你不应该修改 Vue 原型……在我看来,这不是最佳实践(只是我的 PTSD 是从使用默认对象原型调试项目开始的到处都是非标准的属性,弄乱了一切,创造了各种令人讨厌的错误)。如果你有某种状态管理框架,比如 Vuex,我建议将这些数据存储在 Vuex 状态中。

      或者破解一切,你不需要将数据从窗口对象复制到 Vue.prototype

      (window as any).static_url
      

      【讨论】:

        猜你喜欢
        • 2016-09-07
        • 2018-02-17
        • 2019-06-28
        • 1970-01-01
        • 2013-02-27
        • 2015-10-11
        • 2018-01-01
        • 1970-01-01
        • 2020-03-25
        相关资源
        最近更新 更多