Is there a shorter way to manage a list of matching values for the same variable in a Typescript IF statement?
if(X==5 || X==undefined || X=="") {
//do something...
}
Syntactically, you can use switch instead of if to test for multiple values using repeating cases:
switch (x) {
case 5:
case "":
case undefined:
// do something
break;
}
But this is rarely done.
To programatically test for multiple values, you can put the values in an array and check that it includes your argument value using indexOf:
if ([5, "", undefined].indexOf(x) >= 0) {
...
}
Note that this will create the values array each time, so if this check repeats you might want to create the array once, elsewhere, and reuse it.
const values = [5, "", undefined];
// elsewhere
if (values.indexOf(x) >= 0) {
...
}
In fact, if the number of values to test is large, you might want to put them in a Set and check that it has them, as this is faster than testing against an array:
const values = new Set(5, "", undefined);
// elsewhere
if (values.has(x)) {
...
}