tingyuan
tingyuan

Reputation: 29

vue3 typescript question, how to fix ts(2305) error?

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

Why there is such error report? I am not clear, how to fix it?

Upvotes: 3

Views: 10651

Answers (2)

Amos Wong
Amos Wong

Reputation: 192

you have to put the new declaration in the main.ts file

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

Seems to only work when the declare statements are placed in a ts file (not .d.ts file). e.g.

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

From Vue documentation

Information about this is also added to the Vue's documentation.

See: https://v3.vuejs.org/guide/typescript-support.html#augmenting-types-for-globalproperties (Added in vuejs/docs-next#723)

Make sure the declaration file is a TypeScript module

In order to take advantage of module augmentation, you will need to ensure there is at least one top-level import or export in your file, even if it is just export {}.

In TypeScript, any file containing a top-level import or export is considered a 'module'. If type declaration is made outside of a module, it will overwrite the original types rather than augmenting them.

Upvotes: 3

tingyuan
tingyuan

Reputation: 29

Global declare module will override the original declaration, so module "@vue/runtime-core" will be overwritten, while "vue" relies on "@vue/...", which leads to such error.

The correct way is to place "declare module '@vue/runtime-core'" to a different .d.ts file.

Upvotes: -1

Related Questions