vuex-smart-module icon indicating copy to clipboard operation
vuex-smart-module copied to clipboard

Property 'auth' has no initializer and is not definitely assigned in the constructor

Open notflip opened this issue 3 years ago • 1 comments

I would like to use data from the auth module, in the gallery module (to get the current signed in user) However TS is complaining about the auth variable inside my GalleryActions class TS2564: Property 'auth' has no initializer and is not definitely assigned in the constructor.

Am I missing something? Thank you.

auth module

class AuthState {
    user?: User
    authenticationError?: string
}

export const auth = new Module({
    state: AuthState,
    getters: AuthGetters,
    mutations: AuthMutations,
    actions: AuthActions
})

gallery module

import {auth as authModule} from './auth'

class GalleryActions extends Actions<GalleryState, GalleryGetters, GalleryMutations, GalleryActions> {

    auth: Context<typeof authModule> // <--------------------- errored line

    $init(store: Store<any>): void {
        this.auth = authModule.context(store)
    }
}

notflip avatar Oct 23 '21 04:10 notflip

You have to help to the TS compiler using Non-null assertion operator

import {auth as authModule} from './auth'

class GalleryActions extends Actions<GalleryState, GalleryGetters, GalleryMutations, GalleryActions> {

    auth!: Context<typeof authModule> // Just add "!" after the module name

    $init(store: Store<unknown>): void {
        this.auth = authModule.context(store)
    }
}

You can see this trick here: https://github.com/ktsn/vuex-smart-module#mocking-nested-modules-and-dependencies

vdkrasny avatar Jul 17 '22 09:07 vdkrasny