简体   繁体   中英

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM