簡體   English   中英

Typescript 使用狀態聯合類型

[英]Typescript UseState 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;

而且我希望const [userInfos, setUserInfos] = useState<TUserInfos>{}只采用其中一種類型,但是當我嘗試訪問userInfos時,只有password可用。

有人可以向我解釋嗎?

否則,您將需要一個歧視聯盟,對於 TypeScript 它可以是一個或另一個,因此它只識別它們共享的內容,在您的情況下為password 請注意,兩者都添加了type

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;

您需要進行類型檢查才能擁有一個或另一個:

if(userInfo.type === "login"{
  // you can access IUserInfosLogin properties here
}else{
 // you can access IUserInfosRegister properties here
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM