簡體   English   中英

Typescript - Function 返回類型如果我想返回 object

[英]Typescript - Function return type if I want to return object

注意:請在回答前通讀。 這看起來像一個簡單的問題,但我不確定它是否那么簡單。 另外,我是 typescript 的新手,所以 go 對我來說很容易:p

所以這里是用例。 我有一個 model 用戶,我寫了一個通用的 function 來根據數據庫中的 email 檢查用戶是否存在。 如果存在,則返回用戶 object。

現在,如果它是任何其他 object,那么我可以定義類型並繼續使用我的代碼,但它是我從 DB 獲得的用戶 object,不知道如何解決這個問題。

我通過提到返回類型“any”找到了解決方法,但我的靈魂對此並不平靜。 這感覺更像是一個 hack,而不是一個解決方案。

廢話不多說,代碼如下:

export const existingUser = async (email: string): Promise<any> => {
  const foundUser = await User.findOne({ email: email });
  return foundUser;
};

現在,正如我上面提到的那樣,這是可行的,但我嘗試了一種不同的方法,即拋出錯誤。 我已經定義了我的用戶 model 類型,如下所示:

export interface Iuser extends Document {
  profile_picture_url?: string;
  first_name: string;
  last_name: string;
  email: string;
  password: string;
  phone_number?: string;
  is_agree_terms_at: string;
  gender?: Gender;
  role: UserRole;
  isValid: boolean;
}

然后提到 Iuser 作為我的返回類型,因為這是我期望從 DB 獲得的 object 的類型。 我知道一旦將其添加到數據庫中,它將具有其他字段,但我不知道更好-_-

export const existingUser = async (email: string): Promise<Iuser> => {
  const foundUser = await User.findOne({ email: email });
  return foundUser;
};

請幫幫我。 我無法入睡。

第一個問題-您的 function 是async的,它返回 promise,因此您需要將Iuser包裝在 promise 類型中-

// NOTE: This code doesn't work just yet, there are more issues
export const existingUser = async (email: string): Promise<Iuser> => {
  const foundUser = await User.findOne({ email: email });
  return foundUser;
};

第二個也是主要問題 - 如果您檢查.findOne的返回類型 - 您會注意到它返回聯合類型 - 它找到的文檔null (以防您的查詢不匹配任何內容)。

這意味着foundUser的類型實際上是Iuser | null Iuser | null ,但您將其視為Iuser - 這是不兼容的。

你可以做的是——

export const existingUser = async (email: string): Promise<Iuser | null> => {
  const foundUser = await User.findOne({ email: email });
  return foundUser;
};

這也將返回Iuser | null Iuser | null

或者,如果您100% 確定用戶必須存在-

export const existingUser = async (email: string): Promise<Iuser> => {
  const foundUser = await User.findOne({ email: email });
  return foundUser!;
};

! 運算符斷言類型不是 null

或者,如果您想在找不到用戶時拋出異常-

export const existingUser = async (email: string): Promise<Iuser> => {
  const foundUser = await User.findOne({ email: email });
  if (!foundUser) {
      throw new Error('User not found');
  }
  return foundUser;
};

Check out using mongoose with typescript to get a general understanding about how to bake your Iuser type directly into your mongoose model - which will let the type system do all the type inferring work for you in this case.

暫無
暫無

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

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