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