I have this union type:
export interface IUserInfosLogin {
usernameOrEmail: string;
password: string;
}
export interface IUserInfosRegister {
username: string;
email: string;
password: string;
passwordConfirm: string;
}
export type TUserInfos = IUserInfosLogin | IUserInfosRegister;
And I would like a const [userInfos, setUserInfos] = useState<TUserInfos>{} to take just one of these types, but when I try to access userInfos only password is available.
Can someone explain it to me?
>Solution :
You would need a Discriminating Union as otherwise, for TypeScript it can be one or another, so it only recognises what they share, in your case password. Notice that type added on both:
export interface IUserInfosLogin {
type:"login";
usernameOrEmail: string;
password: string;
}
export interface IUserInfosRegister {
type:"register"
username: string;
email: string;
password: string;
passwordConfirm: string;
}
export type TUserInfos = IUserInfosLogin | IUserInfosRegister;
An you would need a type checking, in order to have one or another:
if(userInfo.type === "login"{
// you can access IUserInfosLogin properties here
}else{
// you can access IUserInfosRegister properties here
}