tslint complaining "statements must be filtered with an if statement" when using switch – Tslint

Photo of author
Written By M Ibrahim
angular angular-cli reacttypescript tslint

Quick Fix: Use an if statement to filter the switch statement. For example:

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

    }
  }
}

The Problem:

Problem Statement:

In a TypeScript method, when using a switch statement to handle different cases based on the value of a variable, TSLint raises an error stating "statements must be filtered with an if statement." Despite the switch statement acting as a form of if-else-if condition, TSLint does not recognize it as such, leading to lint errors.

The Solutions:

Solution 1: Use an If Statement to Filter Object Properties

To address the issue of TSLint complaining about “statements must be filtered with an if statement” when using a switch statement, you can use an “if” statement to filter the object properties before entering the switch block. Here’s how you can do it:

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

This solution ensures that the switch statement is only executed for properties that exist in the “state.errors” object.

Solution 2: Separate Type for Factory

You can refactor the code to not use for .. in and make it easier to maintain and develop as well.
Define an interface for the error message factory, and create an object that maps error names to factory functions.
Then, use the factory functions to generate the error messages.
Here is an example:

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