我有这个接口用于在redux工具包中创建切片
interface AuthState {
authenticated: boolean;
role: number;
currentUser: IUser | null;
isAuthenticating: boolean;
}
如果authenticated
为真,有没有办法使currentUser
始终为IUser
?
因此,当访问currentUser时,我不必检查possibly null
。我是ts
的新手
您可以使用一个可区分的并集,在authenticated
上进行区分,然后与公共属性相交:
type AuthStateUnion = {
authenticated: true;
currentUser: IUser;
} | {
authenticated: false;
currentUser: null;
}
type AuthState = AuthStateUnion & {
role: number;
isAuthenticating: boolean;
}
let state: AuthState = Math.random() > 0.5 ? {
authenticated: true,
currentUser : { name: ""},
role: 1,
isAuthenticating: false
} :{
authenticated: false,
currentUser : null,
role: 1,
isAuthenticating: false
}
if (state.authenticated) {
state.currentUser.name
} else {
state.currentUser // null
}
游乐场链接