我正在Nuxt和Typescript中使用VueX。我希望用户的初始状态为null。设置state.authenticatedUser:null
很好。但是,一旦我尝试为其分配IAuthenticatedUser,它将不知道类型,因为我分配了null,并且在我放置注释的突变中会引发错误。
那么我怎样才能使authenticatedUser最初为null?
import { getAccessorType, mutationTree, actionTree } from 'nuxt-typed-vuex';
import IAuthenticatedUser from '~/ts/interfaces/firebase/user/authenticated_user.ts';
import * as counter from './counter';
type RootState = ReturnType<typeof state>
export const state = () => ({
authenticatedUser: {} as IAuthenticatedUser, //I want this to be null
})
export const getters = {
}
export const mutations = mutationTree(state, {
setAuthenticatedUser(state, newValue: IAuthenticatedUser) {
state.authenticatedUser = newValue // If state.authenticateUser == null I cannot asign newValue becuase state.authenticateUser has a type of null
},
logOut(){
state.authenticatedUser = null; // I cannot do this since it not of type IAuthenticatedUser
}
})
export const actions = actionTree(
{ state, getters, mutations },
{
async onAuthenticationStateChangedAction({ commit, dispatch }, { authUser, claims }) {
if (!authUser) {
commit('logOut');
return
}
const { uid, email, emailVerified, displayName, photoURL } = authUser
commit('setAuthenticatedUser', {
uid,
email,
emailVerified,
displayName,
photoURL,
})
}
}
)
export const accessorType = getAccessorType({
actions,
getters,
mutations,
state,
modules: {
counter,
},
})
答案 0 :(得分:0)
为状态定义一个类,将其初始化为null并声明state
应该属于该类
export class RootState {
authenticatedUser: (IAuthenticatedUser | null) = null
}
export const state: RootState = {} as RootState;
authenticatedUser
将是null
,直到您为其分配
state.authenticatedUser = {} as IAuthenticatedUser
由于类型被声明为允许空值,因此以后您还应该能够再次分配空值。
state.authenticatedUser = null