类型“CombinedVueInstance<Vue, {}, {}, {}, Readonly<Record<never, any>>> 上不存在属性“XXX”

新手上路,请多包涵

我使用 TypeScript 创建了一个 vue 组件,但在 data()methods() 中出现此错误:

 Property 'xxx' does not exist on type 'CombinedVueInstance<Vue, {},
{}, {}, Readonly<Record<never, any>>>'.

例如:

 33:18 Property 'open' does not exist on type 'CombinedVueInstance<Vue, {}, {}, {}, Readonly<Record<never, any>>>'.
    31 |         methods: {
    32 |             toggle: function () {
  > 33 |                 this.open = !this.open
       |                  ^
    34 |                 if (this.open) {
    35 |                     // Add click listener to whole page to close dropdown
    36 |                     document.addEventListener('click', this.close)

此错误也会在任何时候显示 this.close() 被使用。

这是组件:

 <script lang='ts'>
    import Vue from 'vue';
    import axios from 'axios'
    export default Vue.extend({
        data: function () {
            return {
                open: false
            }
        },
        computed: {
            profilePath: function () {
                return "/user/" + this.$store.state.profile.profile.user.id
            }
        },
        methods: {
            toggle: function () {
                this.open = !this.open
                if (this.open) {
                    // Add click listener to whole page to close dropdown
                    document.addEventListener('click', this.close)
                }
            },
            close: function () {
                this.open = false;
                document.removeEventListener('click', this.close)
            }
        }
    })
</script>

是什么导致了这个错误?它似乎仍然在开发中构建错误,但是当我部署到生产环境时它们会导致问题。

原文由 Qwertie 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.6k
1 个回答

如 Vue 文档的 Typescript Support 部分所述:

由于 Vue 声明文件的循环性质,TypeScript 可能难以推断某些方法的类型。出于这个原因,您可能需要在 render 和 computed 中的方法上注释返回类型。

在您的情况下,您应该将 profilePath: function () { 更改为 profilePath: function (): string {

如果您有一个返回值的 render() 方法,但没有 : VNode 注释,您可能会遇到相同的错误。

原文由 Tiago 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题