Search code examples
typescriptvue.jsvuex

`direct-vuex` has error when defining Getters: "Function implicitly has return type 'any'..."


I'm using direct-vuex package to define the store for Vuejs+Typescript. I have this error when trying to define Getters:

'userGetters' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.ts(7022)

I can access store.getters.canUpdateUsers from my component but the getter is just executed one time and the type of getters is any. This is the exact type of store.getters:

(property) getters: {
    [x: string]: any;
    user: {
        [x: string]: any;
    };
}

This is the getter part of my module:

export const userGetters = defineGetters<UserState>()({
    canUpdateUsers(...args) {
        // const { state } = userGetterContext(args);
        const { state, getters, rootState, rootGetters } = mod1GetterContext(args)
        console.log(state);

        return (
            state.currentUser.role == "admin" ||
            state.currentUser.role == "presenter"
        );
    },
});
const mod1GetterContext = (args: [any, any, any, any]) => moduleGetterContext(args, userModule)

And this is the module itself:

export const userModule = defineModule({
  state: {
    userList: [],
    currentUser: {},
  } as UserState,

  actions: userActions,
  mutations: userMutations,
  getters: userGetters,
});

I already disabled no-use-before-define eslint rule. It seems that it's not related to this error.

Update:

I reproduced the error in this sandbox:

https://codesandbox.io/s/spring-dew-e5xrq?file=/src/store/modules/user/userGetters.ts


Solution

  • As mentioned in the document, the return type of getters should be declared explicitly when using moduleGetterContext:

    Types in the context of actions implies that TypeScript should never infer the return type of an action from the context of the action. Indeed, this kind of typing would be recursive, since the context includes the return value of the action. When this happens, TypeScript passes the whole context to any. Tl;dr; Declare the return type of actions where it exists!

    For the same reason, declare the return type of getters each time a getter context generated by moduleGetterContext is used!

    https://github.com/paroi-tech/direct-vuex#in-a-vuex-module

    This is the fixed code:

    export const userGetters = defineGetters<UserState>()({
    
        // The boolean type is defined explicitly
        canUpdateUsers(...args):boolean {
    
            // ...
        }