Enhance the Nuxt 3 experience by expanding the functionality of the NuxtApp type with

When I include a plugin in my NuxtApp, it correctly identifies its type.

https://i.stack.imgur.com/UFqZW.png

However, when I attempt to use the plugin on a page, it only displays the type as "any." https://i.stack.imgur.com/hVSzA.png

Is there a way for me to manually add types to extend the NuxtApp type? How can I make sure it recognizes the correct type of the plugin?

I was considering something like this:

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

interface PluginsInjections {
  $order: ReturnType<order>
}

declare global {
  interface NuxtApp extends PluginsInjections {}
}

Answer №1

I finally cracked the code!

After some research on how to implement it in the i18n plugin, https://i.stack.imgur.com/HjYZY.png

I followed the same steps for my own project in types/index.d.ts

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

interface PluginsInjection {
  $sort: ReturnType<typeof sort>
}

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

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

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

Now the system recognizes the plugin, providing helpful auto-complete suggestions. https://i.stack.imgur.com/XeJqZ.png

https://i.stack.imgur.com/uz5N7.png

Answer №2

It's unnecessary to manually specify types for properties and functions injected by plugins because it should be done automatically according to the documentation: https://nuxt.com/docs/guide/directory-structure/plugins#typing-plugins. If the automatic detection is not working as expected, you should investigate why.

In more complex scenarios, you might need to define the types of injected properties manually. Here's an 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 { }

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

Keep in mind that manually specifying types can hide the underlying issue in your code instead of addressing the root cause.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The mysterious appearance of the <v-*> custom element in Vuetify Jest

Currently, I am in the process of writing unit tests for my project using Jest. The project itself is built on Vue, Vuetify (1.5), TypeScript, and vue-property-decorator. One particular area of focus for me has been creating a basic wrapper for the <v- ...

Error encountered: The import of 'createLocation' from 'history' failed. This issue occurred due to conflicting versions of History and React-Router-DOM

While attempting to configure an existing project on a new development server, I encountered the following error: ./node_modules/react-router-dom/esm/react-router-dom.js Attempted import error: 'createLocation' is not exported from 'histor ...

Leveraging RXJS for real-time response to keyboard and mouse click combinations in web

I am new to RXJS and looking for a way to drag an HtmlElement when the user presses the space key and then drags the element with the mouse. The dragging should be initiated by either pressing the SPACE key followed by a left click, or vice versa. The dra ...

implement a solution in Ionic 4 Angular 6 that triggers a function only when all the observables in a loop have

In my code, I have a function named getDevices(). This function is responsible for fetching an array of devices. After getting this array, the code iterates through each device and calls another function called updateToServer(). The purpose of updateToServ ...

Syncing data between local storage and a remote server using Ionic5 provider

I've been considering implementing a data provider that could store a duplicate of the backend data locally for quick access. I believe this concept is referred to as mirroring or something similar. Nevertheless, it must be synchronized and updated r ...

Exploring NextJS with Typescript

Struggling to incorporate Typescript with NextJS has been a challenge, especially when it comes to destructured parameters in getInitialProps and defining the type of page functions. Take for example my _app.tsx: import { ThemeProvider } from 'styled ...

Preventing memory leaks in unmounted components: A guide

Currently, I am facing an issue while fetching and inserting data using axios in my useState hook. The fetched data needs to be stored as an array, but unfortunately, I encountered a memory leak error. I have tried various solutions including using clean u ...

Issue with recognizing global methods in Vue and Typescript – help needed

I have a Vue mixin that looks like this: const languageMixin = Vue.extend({ methods: { $getLanguages: function(): object { return { en: 'english' } } } } Vue.mixin(languageMixin) ...

Changing background color during drag and drop in Angular 2: A step-by-step guide

A drag and drop container has been created using Angular 2 typescript. The goal is to alter the background color of the drag & drop container while dragging a file into it. Typescript: @HostListener('dragover', ['$event']) public onDr ...

How to vertically align Material UI ListItemSecondaryAction in a ListItem

I encountered an issue with @material-ui/core while trying to create a ListItem with Action. I am looking for a way to ensure that the ListItemSecondaryAction stays on top like ListItemAvatar when the secondary text becomes longer. Is there any solution to ...

Invoke the method saved as a class attribute

Within my codebase, there exists a class named Process. This class has a constructor that takes in a type of object () => void. Initially, everything seemed to be working perfectly fine when I passed this object into the class. However, issues arose whe ...

Launching a Node.js command-line interface to NPM, developed using TypeScript

I'm struggling with deploying my Node CLI tool to NPM. During development and testing, everything works fine. I can even use `npm link` on the repo without any issues. After successfully publishing and downloading the package, the application crashes ...

Enable the normal back button functionality when new query parameters are added dynamically

Whenever a page is visited without any parameters, I push some parameters to the Nuxt router. This process can be seen in more detail at https://router.vuejs.org/guide/essentials/navigation.html. For example, if someone visits: /program, they will end up ...

HTTP Interceptor never finishes executing (finalization is never triggered)

In my angular 8 project, I created a basic HttpInterceptor that simply duplicates the original request and includes an additional parameter: @Injectable() export class RequestHeadersInterceptor implements HttpInterceptor { intercept(request: HttpReques ...

Mastering ngClass for validation in Angular 2: Step-by-step guide

I am facing an issue with a form I have created where I applied ngclass to display an error when the form value is missing. However, the error is showing up when the form is initially loaded. It seems that by default, my input tag is invalid when the form ...

The best approach to effectively integrate TypeScript and Fetch is by following the recommended guidelines

Currently, I am in the process of learning React and Typescript simultaneously. On the backend side, I have a server set up with ApiPlatform. For the frontend part, my goal is to utilize fetch to either create or update a Pokemon along with its abilities. ...

Having trouble accessing functions in Typescript when importing JavaScript files, although able to access them in HTML

Recently, I started incorporating TypeScript and React into my company's existing JavaScript code base. It has been a bit of a rollercoaster ride, as I'm sure many can relate to. After conquering major obstacles such as setting up webpack correc ...

Getting environment variables on the client side in Next.js: A step-by-step guide

How can I retrieve an environment variable in my Next.js application and pass the data into datadogRum.init? // _app.tsx import React from "react"; import { useEffect } from "react"; import type { AppProps } from "next/app"; ...

Is it possible to rotate an image with a random angle when hovering in Angular?

I'm currently working on a photo gallery project and my goal is to have the images rotate when hovered over. However, I am experiencing difficulties in passing values from TypeScript into the CSS. HTML <div class="back"> <div cl ...

Adjust the selected value in real-time using TypeScript

Hey there, I've got a piece of code that needs some tweaking: <div> <div *ngIf="!showInfo"> <div> <br> <table style="border: 0px; display: table; margin-right: auto; margin-left: auto; width: 155%;"& ...