Home > OS >  Typescript switch statement not working properly
Typescript switch statement not working properly

Time:03-24

For some reason this switch is not reaching any of the cases defined

const resultList = ['pass', 'fail', 'skip']
        for(const result in resultList){
            try {
                const endpoint = 'www.url.com';
                const response = await axios.get(endpoint);
                console.log(endpoint, response)
                if(response.status == 200){
                    console.log('status code good')
                    switch(result){
                        case 'pass':
                            console.log('case = pass');
                            this.passed = response.data;
                            break;
                        case 'fail':
                            console.log('case = fail');

                            this.failed = response.data;
                            break;
                        case 'skip':
                            console.log('case = skip');

                            this.skipped = response.data;
                            break;
                    }
                }
            }
            catch(error) {
                console.log(error)
            }
        }

I am seeing 200 responses from the API, however I never see any of the case logs... what am I doing wrong here?

Thanks in advance for the help

CodePudding user response:

The for...in loop iterate over the keys in a list, in this case:

const resultList = ['pass', 'fail', 'skip']
for(const result in resultList){ 
  console.log(result)
}

Will print

0
1
2

And for this, the condition on the switch fails.

To iterate over the values of a list, use the for...of loop.

for(const result of resultList) { ... }

CodePudding user response:

As expected; the solution was a minor change as highlighted by @kellys comment... the cases were never met because it was using the index as opposed to the value.

const resultList = ['pass', 'fail', 'skip']
        for(const result of resultList)
  • Related