【问题标题】:vue3 typescript question, how to fix ts(2305) error?vue3 typescript 问题,如何修复 ts(2305) 错误?
【发布时间】:2021-02-24 11:18:03
【问题描述】:

declare module '*.vue' {
  import type { DefineComponent } from 'vue' // module "../node_modules/vue/dist/vue" has no exported member “DefineComponent”。ts(2305)
  const component: DefineComponent<{}, {}, any>
  export default component
}

declare module '@vue/runtime-core' {
  export interface ComponentCustomProperties {
      $goto: any
  }
}

为什么会有这样的错误报告?我不清楚,如何解决?

【问题讨论】:

    标签: typescript vue.js vuejs3


    【解决方案1】:

    您必须将新声明放入 main.ts 文件中

    @Zenthae - https://github.com/vuejs/vue-next/pull/982#issuecomment-787105294

    似乎仅在将声明语句放在ts 文件(而不是.d.ts 文件)中时才有效。例如

    src/shim-vue.d.ts

    declare module '*.vue' {
      import type { DefineComponent } from 'vue'
      const component: DefineComponent<{}, {}, any>
      export default component
    }
    

    src/main.ts

    import { createApp } from 'vue'
    import App from './App.vue'
    
    createApp(App).mount('#app')
    
    // Placing it here or any other `.ts` file works
    declare module '@vue/runtime-core' {
      export interface ComponentCustomProperties {
          $goto: any
      }
    }
    

    来自 Vue 文档

    这方面的信息也被添加到了 Vue 的文档中。

    参见:https://v3.vuejs.org/guide/typescript-support.html#augmenting-types-for-globalproperties添加于vuejs/docs-next#723

    确保声明文件是 TypeScript 模块

    为了利用模块扩充,您需要确保文件中至少有一个顶级 importexport,即使它只是 export {}

    In TypeScript,任何包含顶级importexport 的文件都被视为“模块”。如果在模块之外进行类型声明,它将覆盖原始类型而不是扩充它们。

    【讨论】:

      【解决方案2】:

      定义组件应该像下面这样声明

      import { defineComponent } from 'vue'
      
      const Component = defineComponent({
        // type inference enabled
      })
      

      更多detail

      【讨论】:

        【解决方案3】:

        全局声明模块会覆盖原来的声明,所以模块“@vue/runtime-core”会被覆盖,而“vue”依赖于“@vue/...”,会导致这样的错误。

        正确的方法是将“declare module '@vue/runtime-core'”放到不同的.d.ts文件中。

        【讨论】:

          猜你喜欢
          • 2021-01-29
          • 2021-11-06
          • 2021-04-19
          • 2021-07-06
          • 2020-12-19
          • 2021-07-07
          • 2020-10-06
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多