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

Creating custom typings in a typings.d.ts file does not address the issue of importing a JavaScript library

I'm attempting to integrate the Parse-server JS sdk into an angular 8 application, but no matter what approach I take, I encounter errors. Here is what I have tried: Creating custom typings.d.ts files with declare var parse: any; Installing the @ty ...

"Enhancing user experience with MaterialUI Rating feature combined with TextField bordered outline for effortless input

I'm currently working on developing a custom Rating component that features a border with a label similar to the outlined border of a TextField. I came across some helpful insights in this and this questions, which suggest using a TextField along with ...

Inquiry regarding Typescript's array of types

While researching how to declare arrays of types online, I came across the following example: arrayVar: Array<Type> Seems simple enough, so I attempted to declare my variable like this: transactions: Transactions = { total : 0, list: Array<Transa ...

Struggled with setting up the WebSocket structure in typescript

Issue Running the code below results in an error: index.tsx import WebSocket from 'ws'; export default function Home() { const socket = new WebSocket('ws://localhost:1919/ws'); return ( <div>Home</div> ); } ...

The Redux Toolkit Slice is encountering an issue where it generates the incorrect type of "WritableDraft<AppApiError> when the extraReducer is

I defined my initial state as MednannyAppointments[] for data and AppApiError for error. However, when I hover over state.error or state.data in my extraReducer calls, the type is always WritableDraft. This behaviour is confusing to me. Even though I have ...

Troubleshooting issue with jest expect.any() failing to work with a custom class following migration from JavaScript to TypeScript

I recently made the switch to TypeScript in my project, and now some of my Jest tests are failing. It appears that the next function below is no longer being called with an AppError object, but with an Error object instead. Previously, the assertion expec ...

I'm having some trouble with my middleware test in Jest - what could be going wrong?

Below is the middleware function that needs testing: export default function validateReqBodyMiddleware(req: Request, res: Response, next: NextFunction) { const { name, email }: RequestBody = req.body; let errors: iError[] = []; if (!validator.isEmai ...

Error: The TypeScript aliases defined in tsconfig.json cannot be located

Having trouble finding the user-defined paths in tsconfig.json – TypeScript keeps throwing errors... Tried resetting the entire project, using default ts configs, double-checked all settings, and made sure everything was up-to-date. But still no luck. H ...

Having trouble compiling Typescript code when attempting to apply material-ui withStyles function

I have the following dependencies: "@material-ui/core": "3.5.1", "react": "16.4.0", "typescript": "2.6.1" Currently, I am attempting to recreate the material-ui demo for SimpleListMenu. However, I am encountering one final compile error that is proving ...

Angular 8: How to Retrieve Query Parameters from Request URL

Can I retrieve the GET URL Query String Parameters from a specific URL using my Angular Service? For example, let's say I have a URL = "http:localhost/?id=123&name=abc"; or URL = ""; // in my service.ts public myFunction(): Observale<any> ...

Dealing with an AWS S3 bucket file not found error: A comprehensive guide

My image route uses a controller like this: public getImage(request: Request, response: Response): Response { try { const key = request.params.key; const read = getFileStream(key); return read.pipe(response); } catch (error ...

What is the best way to declare a minimum and maximum date in HTML as the current date?

I have a question regarding setting the min/max date for a date input in my Angular 6 project. How can I ensure that only dates up to the current date are enabled? So far, I have attempted to initialize a new Date object in the ngOnInit function and set t ...

Recursive types in TypeScript allow for the definition of types that

Is there a way to implement the function below without utilizing any? Playground type MyType = { name: string, age: number, score: { prime: number, }, prize: { first: { discount: number } } } export const trim = ( myObj: ...

Avoiding Overload Conflicts: TypeScript and the Power of Generic Methods

I have created an interface type as follows: interface Input<TOutput> { } And then extended that interface with the following: interface ExampleInput extends Input<ExampleOutput> { } interface ExampleOutput { } Additionally, I ha ...

Disabling the use of console.log() in a live environment

In an effort to disable console logs for production environments in my angular application, I implemented the code below. While it successfully suppresses logs in Chrome, IE 11 continues to display them. Here is the snippet from main.ts: if (environment. ...

The 'default' export is not found in the 'tailwind.config.js' file

Is it possible to utilize a theme variable for Tailwind within the Nuxt code for Storybook? Although everything appears to be fine during development, I encounter an error when building Storybook stating that ""default" is not exported by "t ...

Customize the text displayed in a dropdown menu in Angular Material based on the selection made

I am working with a multi-select dropdown menu that includes an option labeled "ALL" which, when selected, chooses all available options in the list. My goal is to display "ALL" in the view when this option is chosen or when the user manually selects all t ...

Stop redux useSelector from causing unnecessary re-renders

I'm working on a component in React-Redux that utilizes the useSelector hook to retrieve a dictionary from the Redux store. This dictionary maps UUIDs to objects containing data that I need to display. interface IComponentProps { id: string } const ...

Angular device redirection allows you to automatically redirect users based on the device

Currently in my Angular project, I am attempting to dynamically redirect users based on their device type. For example, if the user is on a Web platform, they will be redirected to www.web.com. If they are on an Android device, they should go to www.androi ...

Access values of keys in an array of objects using TypeScript during array initialization

In my TypeScript code, I am initializing an array of objects. I need to retrieve the id parameter of a specific object that I am initializing. vacancies: Array<Vacancy> = [{ id: 1, is_fav: this.favouritesService.favourites.find(fav = ...