How can I use an array as case parameter in switch case?
switch ("value")
case ArrayOfStrings // check every array item to be match with value
...
No.
This
switch ("value") {
case ArrayOfStrings // check every array item to be match with value
...
does not work, because the value of switch
and the value of case
is checked with a Identity/strict equality operator ===
comparison.
It is not possible to check a value agains a value of the array.
Any other construction, like
switch (true) {
case ArrayOfStrings.includes("value"): // check every array item to be match with value
would work, but if you have only to check a single value and not other constraints, you better take
if (ArrayOfStrings.includes("value")) {
// ...
}
Well first I would suggest using if
with something like Array.isArray
:
if (Array.isArray(value)) {
// check array items
}
But, if you really want/need to check by comparing to Array
constructor:
const check = (value) => {
switch (value.constructor) {
case Array:
console.log('array');
break;
// For example
case Number:
console.log('number');
break;
}
}
check(7); // 'number'
check([]); // 'array'
I would really discourage from using this approach though.
In theory, you could do that to distinguish between different constructors.
class ArrayOfStrings extends Array<string> {};
class ArrayOfNumbers extends Array<number> {};
function main(input: ArrayOfStrings | ArrayOfNumbers): void {
switch (input.constructor) {
case ArrayOfStrings:
console.log('It was an array of strings!');
break;
default:
console.log('It was something else');
}
}
main(new ArrayOfStrings('foo', 'bar')); // Logs 'It was an array of strings!'
main(new ArrayOfNumbers(1, 2)); // Logs 'It was something else'
However, this method has limitations .
input
will be of the same type for each case
— as opposed to being discriminated. See TypeScript Playground .new
keyword. It's better to use if
statements combined with type guards instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.