Search code examples
typescriptvue.jsvuejs2vuex

Vuex Typescript I am getting the error "Member 'someMutation' implicitly has an 'any' type." in the Component.ts file


I am getting the error:

"Member 'someMutation' implicitly has an 'any' type.".

This error appears in my Vue Component in Component.ts file for the mutation, received from Vuex store.

I have the following code in Component.ts:

@WithRender
@Component({
    components: { SomeChildComponent },
})
export default class Component extends Vue {
    constructor() {
        super();
        this.someFunc(this.someComponentMethod);
        // ... some logic
    }
    @Mutation public someMutation;

    private someComponentMethod(str: string) {
        this.someMutation();
    }
}

Code in store for mutations:

const mutations: MutationTree<State> = {
    someMutation(state, name: string): void {
        state.prop = state.prop.filter((el: IEl): boolean => el.name !== name);
    },
};

const c = {
    state,
    getters,
    mutations,
};

const store = new Vuex.Store(c);

I tried some variants like @Mutation public someMutation: void; or @Mutation public someMutation(s: string): void;, but was not successful.

My intention is to solve the issue, not just to turn off the rule NoImplicitAny in tslint.json file.


Solution

  • Based on the source of someMutation, the method takes a string argument called name, and it returns void, which is typed like this:

    (name: string) => void
    

    Since the property is automatically initialized by vuex-class, we can use the definite assignment assertion to avoid the "no initializer" error.

    !: (name: string) => void
    ^
    

    The final result is:

    @Mutation someMutation!: (name: string) => void