首页 > 解决方案 > Typescript - 从类注释中访问类字段

问题描述

使用以下代码:

@Component({
    props: {
        value: String
    },
    mounted() {
        //Do something with `bar`
        this.bar = this.bar + " is now mounted";
    }
})
export default class Foo extends Vue {
     private bar : string = "This element";
}

您在打字稿控制台中收到以下错误,但代码运行正常。

37:14 Property 'bar' does not exist on type 'Vue'.
    05 |    mounted() {
    06 |        //Do something with `bar`
    07 |        this.bar = this.bar + " is now mounted";
       |             ^
    08 |    }
    09 | })

标签: typescriptvue.js

解决方案


您需要为类Component注释提供类型参数,以便编译器知道它this.bar确实存在。

@Component<Foo>({
    props: {
        value: String
    },
    mounted() {
        //Do something with `bar`
        this.bar = this.bar + " is now mounted";
    }
})
export default class Foo extends Vue {
     private bar : string = "This element";
}

此代码编译没有错误。


推荐阅读