【问题标题】:How to perform a forEach loop on a variable defied as string | Array<string>?如何对定义为字符串的变量执行 forEach 循环 |数组<字符串>?
【发布时间】:2021-08-13 05:32:50
【问题描述】:

我正在使用 airbnb typescript 样式指南,并且我定义了这样的类型:

export interface Question {
  id: number;
  type: 'text' | 'multipleOption' | 'checkBox';
  question: string;
  answer: string | Array<string>;
}

创建了一个适合此接口的变量,我需要对答案执行 forEach 以检查某些条件,但我收到一个 linting 错误提示

Property 'forEach' does not exist on type 'string | string[]'.
  Property 'forEach' does not exist on type 'string'

我想执行一项检查,使我能够在不修改指南配置或更改接口问题定义中的类型的情况下执行此 foreach。

我试过了:

if (question.answer.constructor === Array) {
    question.answer.forEach(...)
}

if (Array.isArray(question.answer)) {
    question.answer.forEach(...)
}
if (typeof question.answer !== 'string') {
    question.answer.forEach(...)
}

但以上都没有消除衬里错误。

【问题讨论】:

  • const answers = &lt;Array&lt;string&gt;&gt;question.answer; answers.forEach(...) - 让我知道这是否有效,我会将其作为答案发布。欢呼
  • 后两者看起来不错。
  • I cannot reproduce,这三种方法都可以正常工作。
  • 我对airbnb指南了解不多,但是那个界面设计的很糟糕。将三个问题接口与各自的answer 类型结合起来可能会更好。
  • 你确定这是一个 linter 警告吗?这听起来像是打字稿错误消息。

标签: javascript typescript airbnb-js-styleguide


【解决方案1】:
if (Array.isArray(question.answer)) {
    (question.answer as Array<string>).forEach(...)
}

您也可以这样做以获得统一的代码

    let answers : Array<string> = [];
    if (Array.isArray(question.answer)) {
        answers = [...question.answer];
    } else if (!!question.answer){
        answers = [question.answer];
    }

    answers.forEach(answer => ....)

【讨论】:

  • 不需要这个演员表。 Array.isArray 已经充当了类型保护。
  • 顺便说一句,没有理由克隆阵列。写const answers = Array.isArray(question.answer) ? question.answer : [question.answer];
猜你喜欢
  • 2010-09-20
  • 1970-01-01
  • 2013-11-24
  • 2019-01-05
  • 2013-12-30
  • 1970-01-01
  • 2018-07-04
  • 1970-01-01
  • 2012-08-16
相关资源
最近更新 更多