ktsn / vuex-smart-module

Type safe Vuex module with powerful module features
MIT License
381 stars 19 forks source link

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

Open notflip opened 2 years ago

notflip commented 2 years ago

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)
    }
}
vdkrasny commented 2 years ago

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