Home > other >  How can write switch case for value of a prop of a subject in a ts file
How can write switch case for value of a prop of a subject in a ts file

Time:07-27

I have a object like below:

{a:
          auth?.type === '1' || auth?.type === '2' || auth?.type === '3'
            ? {
                reason: // here i want write switch case 
            : undefined,
}

how can I write a switch case in this situation ?

CodePudding user response:

You can't (reasonably¹), switch is a statement, and where you want to put it, only an expression is valid, not a statement.

While you could have a deeply-nested set of conditional operators (? :) instead, usually, your best bet in this situation is to determine that value before starting your object literal. Deeply-nested sets of conditions are hard to read and hard to debug.

So I'd suggest doing the switch, storing the result in a variable, and then using the variable in the object literal. (I'd give an example, but it's not clear what you want the switch to do, or what your current code is doing.)


¹ Unreasonably you could have an inline function you call there with a switch in it where you return the value you want. Or more reasonably: define a function you'll reuse that returns the value you want, and call it.

  • Related