简体   繁体   中英

How to perform a forEach loop on a variable defied as string | Array<string>?

I am using the airbnb typescript style guideline and I have defined a type like this:

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

A variable that fits this interface is created and I need to perform a forEach on the answer to check some conditions, but I get a linting error saying that

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

I would like to perform a check that enables me to perform this foreach without modifying the guideline configuration or changing the type in the interface Question definition.

I have tried:

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

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

But none of the above removes the lining error.

if (Array.isArray(question.answer)) {
    (question.answer as Array<string>).forEach(...)
}

also you can do this to have a uniform code

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM