简体   繁体   English

如何对定义为字符串的变量执行 forEach 循环 | 大批<string> ?</string>

[英]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:我正在使用 airbnb typescript 样式指南,并且我定义了这样的类型:

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创建了一个适合此接口的变量,我需要在答案上执行 forEach 以检查某些条件,但我收到一个 linting 错误说

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

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 => ....)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 字符串数组的forEach循环 - forEach loop for String array foreach 循环不迭代字符串数组 - foreach loop not iterating over string array 如何使用 foreach 循环创建文本字符串? - How to create a text string using foreach loop? 如何在 forEach 循环和 if 语句中正确返回字符串? - How to properly return string in forEach loop and if statement? 如何在字符串中循环字符串数组 - How to loop a string an array in string 我如何将许多随机生成的整数转换为数组的字符串,以便执行 forEach() 方法来检查 age &gt;= 18 [DESC] - How could I convert many randomly generated integers into a string of an array in order to perform the forEach() method to check if age >= 18 [DESC] 使用for循环将字符串变量分配给数组 - Assign string variable to array using for loop 使用for循环在数组中查找字符串是可行的,但是forEach()在此无效。 为什么以及如何纠正? - Using a for-loop to find a string in an array is working, but forEach() does not here. Why and how to correct? 如何使用 javascript 在数组 object 变量中使用 foreach 循环 - How to use foreach loop in an array object variable using javascript 如何在不改变循环结构的情况下将字符串前置到for循环中的字符串变量? - How to prepend a string to a string variable in a for loop without changing the loop structure?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM