Exploring the process of incorporating types for a Vue plugin

I am currently trying to integrate a self-made plugin for Vue with TypeScript.

However, when I try to use the method from my vue prototype, I encounter an issue where my method $auth is not recognized on type 'myComponent'. I have also included a .d.ts file for the plugin, but I suspect there may be some issues with it. Additionally, I am unsure if the install function is required in the plugin. While some examples do not include it, the documentation states that it is necessary.

My Custom Plugin

import _Vue from 'vue';
import store from '@/store'
import * as firebase from 'firebase';

export default {
    install: (Vue: typeof _Vue, options?: any) => {
        const base = firebase.initializeApp(config);
        const auth = firebase.auth();
        Vue.prototype.$auth = {
            login: async (username: string, pass: string) => {
                return await auth.signInWithEmailAndPassword(username, pass)
            },
            logout: async () => {
                await auth.signOut()
            }
        };
        
        auth.onAuthStateChanged((user: any) => {
            store.commit('updateUser',{ user })
        })
    }
}

myPlugin.d.ts

declare module 'vue/types/vue' {
    interface Vue {
        $auth: {
            login: (username: string, pass: string) => Promise<any>
        };
    }
}

Component Definition

export default class SignUp extends Vue {
    email: string = '';
    password: string = '';

    async onSubmit(){
        if ((this.$refs.form as any).validate()) {
            const auth = await this.$auth.login(this.email, this.password)
        }
    }
}

Answer №1

  1. Installing a function is essential, as Vue internally uses this function in Vue.use(YourAwesomePlugin) to load your plugin.

  2. I did not find success in making the declaration file work as described. However, in the documentation examples, an author incorporated declaration merging within a file containing logic (not in a separate d.ts file). So, by placing the content of your myPlugin.d.ts into the main plugin file, it will bring your interface and ensure that $auth exists on this.

Check out the TypeScript Docs (refer to the Module Augmentation section): Declaration Merging


UPDATE

To enable the .d.ts file to work, simply import Vue into that file.

For further information, visit the Vue docs: Augmenting Types for Use with Plugins

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

What is the best way to add a border around an image along with a button using VueJS?

I am struggling to link a button and an image in VueJS to display a border around the picture. While I can successfully display the border on the button, I am unsure how to extend it to the image as well. Vue.component('my-button', 'my-img& ...

Stop allowing images to automatically open in the browser when a image file is dropped into Vue

Whenever I attempt to drag the image above the label and release the left mouse button, the files open in my browser. Simply adding prevent is not enough to prevent this default behavior. What additional steps do I need to take? Please note that the layou ...

Passing the array as query parameters and retrieving it using the angular getAll function is the most efficient way

When using this function, I extract the ids of items and aim to send them as an array for retrieval with getAll(). const queryParams: Record<string, string[]> = selectedItems.reduce( (acc, curr, index) => ({ ...acc, [&apo ...

Vue project encounters an unexpected Tailwind error during the build process

I have successfully implemented my Vue2 Tailwind CSS project in development mode. However, when trying to run it in production, I am facing an issue: cross-env NODE_ENV=production && npx tailwindcss -i ./src/assets/styles/index.css -o ./dist/tailwi ...

Using TypeScript path aliases to resolve import errors

After creating a Vue.js project using Vue CLI 3 and setting up the import statement with the @ alias, I encountered an error when running npm run build. Can you explain why this happened? Error Message $ npm run build > [email protected] build / ...

You are unable to assign mutations in Vuex

Dealing with a peculiar problem where "val" and "ok" can be used within "console.log()", but for some reason, state.user cannot be assigned any value. However, state.user does display 'ok' on the website. export const state = () => ({ user: ...

Error Message: "Module not found - Module TS2307 cannot be located

When I try to open a Typescript project in VSCode, I encounter the error message "ts2307 Cannot find module 'react' or its corresponding type declarations". However, everything works fine when I use WebStorm. The project was created using Create ...

Error loading resource in Vue npm run serve: net::ERR_CONTENT_LENGTH_MISMATCH

I am encountering the following error message in Google Chrome console: Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH chunk-vendors.js:1 This results in a blank page when attempting to load a Vue development page initiated with: user@ubuntu:~# ...

Struggling to dynamically update array values by comparing two arrays

I am faced with a scenario where I have two arrays within an Angular framework. One of the arrays is a regular array named A, containing values such as ['Stock_Number', 'Model', 'Type', 'Bill_Number'] The other arr ...

Creating interactive carousel slides effortlessly with the power of Angular and the ngu-carousel module

I'm currently tackling the task of developing a carousel with the ngu-carousel Angular module, available at this link. However, I'm facing some challenges in configuring it to dynamically generate slides from an array of objects. From what I&apos ...

Could you provide an explanation of the styled() function in TypeScript?

const Flex = styled(Stack, { shouldForwardProp: (prop) => calcShouldForwardProp(prop), })<LayoutProps>(({ center, autoWidth, autoFlex, theme }) => ({ })); This syntax is a bit confusing to me. I understand the functionality of the code, b ...

"Why is it that in a Vue object, only half the tag is needed in the line 'template: "<App/>'"?

Upon using the Vue webpack template, I came across code that looks like this: /* eslint-disable no-new */ new Vue({ el: '#app', router, template: '<App/>', // <-- components: { App } }) I understand what this code is ...

Steps for Getting Blob Data from Axios in an Express.js Server

I'm currently working on an API that involves sending a Blob Object created in Vue.js to Express.js using Axios.post. Vue.js ... const blobObject = new Blob([content]); axios.post(`http://localhost:3000/post`, blobObject) .then( (resp ...

classes_1.Individual is not a callable

I am facing some difficulties with imports and exports in my self-made TypeScript project. Within the "classes" folder, I have individual files for each class that export them. To simplify usage in code, I created an "index.ts" file that imports all class ...

Vuetify - custom filter for advanced datatable restrictions

Currently, I am faced with a challenge in filtering data from a table where the object names are similar and case sensitive, such as "A", "Aa", or "a". I am struggling to filter the data by these exact values when using a v-select bound to the search funct ...

Encountering a compilation error due to a Typescript assignment

While working with Typescript, I encountered a compilation error in the code shown below: console.log('YHISTORY:login: data = '+data); let theData = JSON.parse(data); console.log('YHISTORY:login: theData = '+JSON.stringify(theData)); ...

Issue with Moment.js: inability to append hours and minutes to a designated time

I have a starting time and I need to add an ending time to it. For example: start=19:09 end=00:51 // 0 hours and 51 minutes I want to add the 51 minutes to the 19:09 to make it 20:00. I've attempted several different methods as shown below, but none ...

Optimizing Materialize-css, Laravel, and VueJS integration: best practices for setting up modals, side-nav, and

Currently, I am in the process of constructing a website utilizing Laravel 5.4, Laravel Mix, VueJS, and Materialize-css. Fortunately, VueJS and jQuery are already integrated with Laravel, so no additional setup is required in that regard. All custom compo ...

Retrieving Information from an Angular 2 Component

Struggling to figure this out, I am attempting to dynamically add user video data that includes a video URL. My goal is to access the data from the component so I can use it in my HTML. I've attempted the following approach. app.component.ts import ...

Sorting through names within a nested array based on specific criteria

I have been struggling to filter by item name for the past day and haven't been successful. The issue lies in my attempt to use a sample array for filtering. While I am able to filter by category successfully, the same cannot be said for filtering by ...