Vyhledávání na webu

Má definice Typescriptu globálních metod pluginů Nuxt typ any?


Napsal jsem plugin pro Nuxt.js, který poskytuje globální metody definované vlastností inject, protože je potřebuji mít přístupné také v instancích Vuex store. Napsal jsem soubor s definicemi typů, který jsem zahrnul do tsconfig.json. Když přistupuji k těmto globálním metodám v mé aplikaci Nuxt.js, například na stránce, funguje psaní typů podle očekávání. Když se pokusím přistoupit k těmto metodám v metodě akce uvnitř store, mají typ any. Jak mohu rozšířit typy v vuex/types/index.d.ts, aby bylo možné přistupovat k mým metodám s podporou intellisense a správnými typy? To by bylo skvělé.

S pozdravem Moritz

Co jsem vyzkoušel:

Po přečtení tohoto průvodce jsem byl schopen dokončit definice typů svých pluginů. Podobným způsobem to musím udělat pro Vuex, ale nemohu přijít na to, který modul mám použít.

plugin-web-connection.ts:

export default ({store, isHMR, app}, inject) => {

  app.store.registerModule('oauth', oAuthStore);
  app.store.registerModule('app-config', appConfigStore);

  inject("getOAuthCredentials", function(stringProp: string) : string {

    console.log("This is an example for getting oAuth: ", stringProp);
    return stringProp;
  });

  inject("doWebRequest", function<T>(method: string, params: any) : 
Promise<T> {
 // content of method does not matter
    }

plugin-web-connection.d.ts:

// 1. Make sure to import 'vue' before declaring augmented types
import Vue from 'vue'

// 2. Specify a file with the types you want to augment
//    Vue has the constructor type in types/vue.d.ts
declare module 'vue/types/vue' {
  // 3. Declare augmentation for Vue
  interface Vue {
    $getOAuthCredentials(stringProp: string): string,
    $doWebRequest<T>(method: string, params: any, storeCommit: string): 
Promise<T>
  }
}

menu-store.ts:

export const state = (): sabioTree => ({

});

export const mutations = {
    setMenu(state: sabioTree, newState: sabioTree) {}
}

export const actions = {

    retrieveMenu(context: any, data: any) {

        var method: string = data.method;
        var parametersObj: any = data.parameters;
        var storeCommit: string = data.storeCommit;

        debugger;

        // this is underlined red by VS-Code because of the generic!! this.$doWebRequest has type any
        this.$doWebRequest<sabioTree>(method, parametersObj, storeCommit).
        then(function(s) {})
    }
 }

Související články