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)
new Vue({
    router,
    render: h => h(Frame)
}).$mount('#app')

... and I'm attempting to utilize it in a component:

<template lang="pug">
    .languages
        a( v-for="language, code in $getLanguages()" :key="code" @click="$root.$i18n.locale = code") {{ language }}&nbsp;
</template>

<script lang="ts">
import Vue from 'vue'
export default Vue.extend({
    methods: {
        languagesList: function () {
            console.log(this.$getLanguages)
        }
    }
})
</script>

However, I encounter an error message that reads "Property '$getLanguages' does not exist on type 'CombinedVueInstance>>'"

Interestingly, the function works when used in the template as the language names are displayed. It's just the TypeScript code that does not recognize the function.

Answer №1

If you want to enhance the vue module by adding a typing for $languages, consider the following:

// vue-shim.d.ts

declare module 'vue/types/vue' {
  interface Vue {
    $languages: LanguageService
  }
}

Here's an example of a psuedo LanguageService:

// language-service.d.ts

export interface LanguageService {
  $languages: () => Record<string, string>
}

To learn more about how to augment Vue, check out this resource.

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

React slick slider not functioning properly with custom arrows

"I have encountered an issue while trying to implement multiple sliders in my component with custom arrows positioned below each carousel. Despite following the documentation meticulously, the arrows do not respond when clicked. What could possibly be ...

Using the value from the Vuex state to set the initial value for a different parameter

I am facing an issue with utilizing an array of objects in my Vuex state to set a default value for another parameter, specifically for mainAccount: For instance: const store = new Vuex.Store({ state: { AccountNums: [ { label: 'M ...

Is it possible to retrieve a variable from a geojson file using Vue 3 and Vite?

For my Vue 3 project, I am trying to import a variable from a geojson file. However, when I use import line from '@static/line.geojson', my page goes blank and it seems like Vue stops working. If I use import line from '@static/line.json&ap ...

Avoiding the sudden appearance of unstyled content in Single-File Components

I am looking to update my HTML navigation <div id="header-wrapper"> <div id="header-logo-title"> <nav> <ul id='mainNav'> <li>Home</li> </ul> </nav> ...

I am facing an issue in my Vue.js/Vite application where importing variables via additionalData becomes unavailable when using @use 'sass:color'

Currently, I am incorporating Vue.js with Vitest along with the sass loader. An issue arises when using @use 'sass:color' in either an inline SCSS file or within a component. It appears to override variables that are defined in css.preprocessorO ...

Issue with `rxjs/Subject.d.ts`: The class `Subject<T>` is incorrectly extending the base class `Observable<T>`

I found a sample template code in this helpful tutorial and followed these two steps to get started - npm install // everything went smoothly, created node_modules folder with all dependencies npm start // encountered an error as shown below- node_mo ...

The term 'Employee' is typically used as a classification, but in this context, it is being treated as a specific value

I am encountering an issue while trying to define a variable as type Employee. The error message 'Employee' only refers to a type but is being used as a value here. ts(2693) keeps appearing. Here is my show-api.ts code: import { Component, OnIni ...

Discover the type of generic keyof in TypeScript

My types implementation is structured as follows: type GenericType<T, K extends keyof T = keyof T> = { name: K; params: T[K] } type Params = { a: 1; b: 2; } const test: GenericType<Params> = { name: "a", params: 2 } ...

The RxJs Observer connected to a websocket only triggers for a single subscriber

Currently, I am encapsulating a websocket within an RxJS observable in the following manner: this.wsObserver = Observable.create(observer=>{ this.websocket.onmessage = (evt) => { console.info("ws.onmessage: " + evt); ...

The Angular4 HTTP POST method fails to send data to the web API

Whenever I make a http post request, it keeps returning an error message saying "data does not pass correctly". I have tried passing the data through the body and also attempted using json.stringify(). Additionally, I experimented with setting the content ...

Having some trouble while attempting to set up the next-auth@beta package due to an error

Currently encountering the following error message: code EUNSUPPORTEDPROTOCOL Unsupported URL Type "workspace:": workspace:* I have made sure to update my node to the most recent recommended version. In a previous project, I successfully instal ...

What is the recommended approach in Angular for unassigned @Input() variables when using TypeScript strict mode?

Issue at Hand After upgrading my Angular version from 10 to 13, I encountered a problem with the new TypeScript strict compiler mode. The upgrade required me to assign values to all declared variables upon initialization, causing issues with properties de ...

Getter and Setter Implementation in Typescript without Using Classes

Check out these various SO questions discussing Typescript getters/setters: from 2015, Jan 2018, Sept 2018, and more. Now, the question arises - what is the best approach to define Typescript types for getters/setters in a plain JavaScript object without ...

Tips for utilizing *.vue components (SFC files) without relying on vue cli

One thing that's been giving me trouble is figuring out how to use *.vue components when I install vue using a CDN. Is it even possible? I'm referring to these template files: <template> </template> <script> </script ...

Importing ES6 modules again

When I import my modules from main.js : import Vue from 'vue' import store from './vuex/store' import VueResource from 'vue-resource' Vue.use(VueResource); import Component from './components/component.vue'; In t ...

Avoid making API calls in every ngOnInit() function

I am currently developing an Angular front-end for a web-based application. One of the challenges I am facing is that all sub-page drill downs, implemented as different Angular components, make identical API calls in the ngOnInit() method. This repetitiv ...

Defining TypeScript class events by extending EventEmitter

I have a class that extends EventEmitter and is capable of emitting the event hello. How can I properly declare the on method with a specific event name and listener signature? class MyClass extends events.EventEmitter { emitHello(name: string): void ...

Replacing a function in TypeScript

Looking to alter the behavior of the alert function in TypeScript? You can achieve this by creating a new function that wraps around the original alert and modifies its behavior. alert = (function (origAlert) { return function (...messages: any[]) { ...

Whenever the return condition is false, make sure to subscribe to the Angular CanActivate Guard

In my UserAccessGuard class, I have a method that captures the current path and compares it to the user's available paths. However, I am facing asynchronous problems because the condition inside the subscribe block causes my Hasaccess variable to rema ...

Error message in CodeSandBox with Angular: TypeError - The function html2canvas_1.default is not defined or recognized

Attempting to convert a basic html table into a PDF format within my project has resulted in unexpected errors when using CodeSandbox: ERROR TypeError: html2canvas_1.default is not a function at AppComponent.downloadPDF (https://3d3bh.csb.app/src/app/a ...