【问题标题】:Typescript - Property 'forEach' does not exist on type 'never'打字稿-“从不”类型上不存在属性“forEach”
【发布时间】:2021-11-12 16:39:08
【问题描述】:

我有 typescript 函数,它接受多种对象类型,需要根据“toAddresses”参数的对象类型做一些事情,但我不断收到 2 个错误。

function createEmailClient(fromAddress: string | Email, toAddresses: (string | Email)[], subject: string, content: string, contentType: ContentType): EmailClient {
  const recipientAddresses: Email[] = []

  if (typeof toAddresses === 'string') {
    toAddresses.forEach(function (address) {
       const recipientEmail: Email = {
          email: address.toString(),
          senderName: ''
       }
      recipientAddresses.push(recipientEmail)
    })
  } else if (typeof toAddresses === 'Email') {
     recipientAddresses.push(toAddresses)
  }
  1. 对于数组迭代,“never”类型上不存在“属性“forEach”。
  2. 此条件将始终返回 'false',因为类型 '"string" | "号码" | "大字" | “布尔” | “象征” | “未定义” | “对象” | "function"' 和 '"Email"' 没有重叠。ts(2367)

有没有办法解决这个问题?

【问题讨论】:

  • 请提供minimal reproducible example,清楚地表明您所面临的问题而没有其他不相关的问题。理想情况下,有人可以将代码放入像The TypeScript Playground (link here!) 这样的独立 IDE 中,然后立即着手解决问题,而无需首先重新创建它。所以应该没有拼写错误、不相关的错误或未声明的类型或值。
  • 它无法编译您的 if 块,因为您正在对不是数组的值进行类型检查。 string 永远不会有 forEach 属性。 pushEmail 可能会遇到同样的问题。
  • 您在运行时使用the typeof operator 测试一个数组,并且始终是"object"。即使数组包含字符串元素,它也不会是"string",而且它肯定不会是"Email",因为这不是typeof 永远返回的那种东西。看来您对 TS 的静态类型系统和类型擦除感到困惑。

标签: typescript


【解决方案1】:

我相信你想做这样的事情:

function createEmailClient(fromAddress: string | Email, toAddresses: Email | string[], subject: string, content: string, contentType: ContentType): EmailClient {
  const recipientAddresses: Email[] = []

  if (Array.isArray(toAddresses)) {
    toAddresses.forEach(function (address) {
       const recipientEmail: Email = {
          email: address.toString(),
          senderName: ''
       }
      recipientAddresses.push(recipientEmail)
    })
  } else {
     recipientAddresses.push(toAddresses)
  }
}

【讨论】:

  • Email | string[](string | Email)[] 不同
  • 确实如此,但我认为这是代码其余部分试图做的一个小故障。
猜你喜欢
  • 2017-03-02
  • 2021-09-07
  • 2020-08-13
  • 2020-09-28
  • 1970-01-01
  • 2017-08-07
  • 2017-03-26
  • 2017-09-06
  • 2020-05-21
相关资源
最近更新 更多