Vue3 TypeScript问题,如何修复ts(2305)错误?

3

enter image description here

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
  }
}

为什么会出现这样的错误报告?我不清楚该如何修复它?
3个回答

3
你需要将新的声明放在 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-globalpropertiesvuejs/docs-next#723中添加

确保声明文件是TypeScript模块

为了利用模块增强功能,您需要确保文件中至少有一个顶层importexport,即使它只是export {}

在TypeScript中,任何包含顶层importexport的文件都被视为“模块”。如果类型声明在模块外部进行,则会覆盖原始类型而不是增强它们。


-1

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

import { defineComponent } from 'vue'

const Component = defineComponent({
  // type inference enabled
})

更多详情


-1

全局声明模块将覆盖原始声明,因此模块“@vue/runtime-core”将被覆盖,而“vue”依赖于“@vue/...”,这导致了这样的错误。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接