【发布时间】:2017-10-31 05:09:47
【问题描述】:
假设我有以下方法:
getErrorMessage(state: any, thingName?: string) {
const thing: string = state.path || thingName;
const messages: string[] = [];
if (state.errors) {
for (const errorName in state.errors) {
switch (errorName) {
case 'required':
messages.push(`You must enter a ${thing}`);
break;
case 'minlength':
messages.push(`A ${thing} must be at least ${state.errors['minlength'].requiredLength}characters`);
break;
case 'pattern':
messages.push(`The ${thing} contains illegal characters`);
break;
case 'validateCardNumberWithAlgo':
messages.push(`Card doesnt pass algo`);
break;
}
}
}
return messages;
}
当我跑步时
ng lint
我收到以下错误:
for (... in ...) 语句必须用 if 语句过滤
查看类似的question 我认为该答案不适用于我的情况。毕竟 switch 语句属于 if-else-if 阶梯的类别。
tslint 应该将 switch 语句视为 if 语句的形式,但事实并非如此?!
【问题讨论】:
-
使用 if else 代替 switch?
-
如果我要检查 100 个条件,你会建议同样的事情吗?
-
我实际上建议您将内部 for 循环重构为其他内容。 :) 方法调用,或者映射错误数组以创建错误消息列表。 :)
-
@toskv 我认为关键是规则说
if语句应该在for...in之后,而switch 语句可以看作是if语句的一种,然而它不能解决错误。
标签: angular typescript angular-cli tslint