簡體   English   中英

類型為 String 時如何在 DB 中查找項目 | String[] 使用 typescript 聯合類型

[英]How to look for an item in DB when the type is String | String[] using typescript union types

我正在調用一個方法sendEmail將 email 發送給單個用戶或一組用戶(到 email 的類型是string | string[]

是否有更清潔/更好的方法來確定它是數組還是單個用戶,以便我可以相應地在數據庫中查找它? 代碼現在看起來很重復。

  public async sendEmail(
    toEmail: string | string[],
  ): Promise<void> {
    if (!Array.isArray(toEmail)) {
      const user = await this.userRepository.getUserByEmail(toEmail);
      await checkIfPaymentMade(user);
    } else {
      for (const email of toEmail) {
       const user = await this.userRepository.getUserByEmail(toEmail);
        await checkIfPaymentMade(user);
      }
    }
  }

想到了一些其他的選擇

  1. 將通用代碼提取到自己的function中。 仍然有一些重復,但只有一行而不是助手 function 需要的長度。
public async sendEmail(
  toEmail: string | string[]
): Promise<void> {
  if (!Array.isArray(toEmail)) {
    await doStuff(toEmail);
  } else {
    for (const email of toEmail) {
      await doStuff(email);
    }
  }
}

private async doStuff(toEmail: string): Promise<void> {
  const user = await this.userRepository.getUserByEmail(toEmail);
  await checkIfPaymentMade(user);
}
  1. 讓 function 的主體僅適用於獨立字符串。 如果是數組,遞歸。
public async sendEmail(
  toEmail: string | string[],
): Promise<void> {
  if (Array.isArray(toEmail) {
    for (const email of toEmail) {
      await sendEmail(email)
    }
  } else {
    const user = await this.userRepository.getUserByEmail(email);
    await checkIfPaymentMade(user);
  }
}
  1. 讓 function 的主體僅適用於 arrays。 如果不是數組,先把它變成一個。
public async sendEmail(
  toEmail: string | string[],
): Promise<void> {
  const emailArray = Array.isArray(toEmail) ? toEmail : [toEmail];

  for (const email of emailArray) {
    const user = await this.userRepository.getUserByEmail(email);
    await checkIfPaymentMade(user);
  }
}

如果您只想保持干燥,這里有一個選項:

TS Playground 鏈接

public async sendEmail (recipients: string | string[]): Promise<void> {
  for (const address of Array.isArray(recipients) ? recipients : [recipients]) {
    const user = await this.userRepository.getUserByEmail(address);
    await checkIfPaymentMade(user);
  }
}

暫無
暫無

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

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