Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript UseState Union Type

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading