tslint抱怨"语句必须使用if语句过滤"使用开关

时间:2017-05-30 16:08:55

标签: angular typescript angular-cli tslint

假设我有以下方法:

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

我收到以下错误:

必须使用if语句

过滤

for(... in ...)语句

看一下类似的question我不认为答案适用于我的情况。所有switch语句都在if-else-if阶段的类别中。

tslint应该将switch语句视为if语句的形式,但它不是吗?!

2 个答案:

答案 0 :(得分:18)

这让我很好奇,所以我查看了TSlint source code这个规则。它有一个名为isFiltered的函数,它似乎只检查ts.SyntaxKind.IfStatement,而不是ts.SyntaxKind.SwitchStatement

function isFiltered({statements}: ts.Block): boolean {
    switch (statements.length) {
        case 0: return true;
        case 1: return statements[0].kind === ts.SyntaxKind.IfStatement;
        default:
            return statements[0].kind === ts.SyntaxKind.IfStatement && nodeIsContinue((statements[0] as ts.IfStatement).thenStatement);
    }

}

因此,除非您想将对象转换为数组,否则您需要使用您提供的链接中的修复程序。 Object.keysif语句:

    for (const errorName in state.errors) {
      if (state.errors.hasOwnProperty(errorName)) {
        switch (errorName) {

有趣的是,你可以拥有任何类型的if语句,错误就会消失。没有检查您是否正在呼叫hasOwnProperty

答案 1 :(得分:4)

该规则旨在阻止您在 for ... 中访问对象原型上定义的属性。

然而,您可以重构代码,以便不使用它,并使其更易于维护和开发。

一个例子是:

interface ErrorMessageFactory {
  (thing: string, state?): string
}

type Errors = 'required' | 'minlength' | 'pattern' | 'validateCardNumberWithAlgo'

let errorFactory: {[e in Errors]: ErrorMessageFactory} = {
  required: (thing) => `You must enter a ${thing}`,
  minlength: (thing, state) => `A ${thing} must be at least ${state.errors['minlength'].requiredLength}characters`,
  pattern: (thing) => `The ${thing} contains illegal characters`,
  validateCardNumberWithAlgo: (thing) => `Card doesnt pass algo`
}



function getErrorMessage(state: any, thingName?: string) {
  if (state.errors) {
    return state.errors.map((error) => errorFactory[error](thingName, state));
  }
  return [];
}

您可以在操场here中看到一个工作代码段。