Home > Net >  Typescript UseState Union Type
Typescript UseState Union Type

Time:08-15

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?

CodePudding user response:

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;

And 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
}

  • Related