Dmytro Afanasiev
Dmytro Afanasiev

Reputation: 191

Nuxt 3 extend NuxtApp type with custom plugins

When i provide plugin to nuxtApp it knows its type

enter image description here

but when i try to use it on the page it show only type "any" enter image description here

Can i add types to extend NuxtApp type mannualy? or what can i do for it to know the right type of plugin?

i think about something like this

import type { order } from '~/plugins/order'

interface PluginsInjections {
  $order: ReturnType<order>
}

declare global {
  interface NuxtApp extends PluginsInjections {}
}

Upvotes: 6

Views: 7996

Answers (2)

Nicolas D
Nicolas D

Reputation: 213

You shouldn't need to manually add types for properties and functions injected by plugins since it's supposed to work automatically as explained in the docs: https://nuxt.com/docs/guide/directory-structure/plugins#typing-plugins Instead, you should investigate why the automatic detection is not working as expected.

More advanced usecases can require you to manually define the types of injected properties. In that case you can follow this example:

// Your plugin
export default defineNuxtPlugin(() => {
  return {
    provide: {
      hello: (msg: string) => `Hello ${msg}!`
    }
  }
})

// index.d.ts
declare module '#app' {
  interface NuxtApp {
    $hello (msg: string): string
  }
}

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $hello (msg: string): string
  }
}

export { }

from: https://nuxt.com/docs/guide/directory-structure/plugins#advanced

But do remember that doing this masks the consequences of another issue in your code base instead of solving the root cause.

Upvotes: 3

Dmytro Afanasiev
Dmytro Afanasiev

Reputation: 191

I figured it out

I looked up how it's done in i18n plugin i18n plugin

and did the same for myself in types/index.d.ts

import type { order } from '~/plugins/order'

interface PluginsInjections {
  $order: ReturnType<typeof order>
}

declare module '#app' {
  interface NuxtApp extends PluginsInjections {}
}

declare module 'nuxt/dist/app/nuxt' {
  interface NuxtApp extends PluginsInjections {}
}

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties extends PluginsInjections {}
}

now it knows that the plugin exists, and helping with auto complete enter image description here

enter image description here

Upvotes: 8

Related Questions