簡體   English   中英

使用switch時,tslint抱怨“語句必須使用if語句進行過濾”

[英]tslint complaining “statements must be filtered with an if statement” when using switch

可以說我有以下方法:

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語句進行過濾

看一下類似的問題,我認為答案不適用於我的情況。 所有switch語句都在if-else-if階段的類別中。

tslint應該將switch語句視為if語句的形式,但它不是?!

這讓我很好奇,所以我查看了這條規則的TSlint源代碼 它有一個名為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

該規則旨在防止您在使用for .. in時訪問在對象原型上定義的屬性。

但是,您可以重構代碼,以便不使用它,並使其更易於維護和開發。

一個例子是這樣的:

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 [];
}

你可以在這里的操場上看到一個工作片段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM