typescript - 如何将用户状态设置为空?
问题描述
我在 Nuxt 和 Typescript 中使用 VueX。我想让我的用户的初始状态为空。设置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,
},
})
解决方案
为将其初始化为 null 并声明为该类的状态定义一个类state
应该可以工作
export class RootState {
authenticatedUser: (IAuthenticatedUser | null) = null
}
export const state: RootState = {} as RootState;
authenticatedUser
然后将null
直到你分配给它
state.authenticatedUser = {} as IAuthenticatedUser
由于该类型被声明为允许为 null,因此您以后也应该能够再次分配 null。
state.authenticatedUser = null
推荐阅读
- angular - 当我尝试将 Angular CLI 与 @ngrx 一起使用时出现错误
- docker - Docker swarm 容器无法解析另一个节点中的容器地址
- julia - 从 jld2 文件加载数据帧对于系统内存来说太大了
- javascript - Is it possible for TypeScript to infer keys from a dynamic object?
- ns2 - NS2:插入延迟器的功能
- mysql - 将字符串转换为整数并在MYSQL中递增
- jquery - JQuery 回调间歇性工作
- c# - 从证书和私钥生成 JWT 不记名令牌
- kotlin - 使用 Null Check Kotlin 附加字符串
- jpa - JPA @ManyToOne CascadeType.PERSIST