如何对定义为字符串的变量执行 forEach 循环 |数组<string>?
How to perform a forEach loop on a variable defied as string | Array<string>?
我正在使用 airbnb 打字稿风格指南,我定义了这样一个类型:
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(...)
}
但是上面的none消除了衬里错误。
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 => ....)
我正在使用 airbnb 打字稿风格指南,我定义了这样一个类型:
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(...)
}
但是上面的none消除了衬里错误。
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 => ....)