Consider the following example:
type BinaryOp = 'MOV'
type UnaryOp = 'ADD' | 'SUB' | 'JRO'
const BinaryOps: BinaryOp[] = ['MOV']
const UnaryOps: UnaryOp[] = ['ADD', 'SUB', 'JRO']
type Line =
{ op: BinaryOp, a: number, b: number }
| { op: UnaryOp, a: number }
Now, let's look at the "pattern match" below:
switch (line.op) {
case 'ADD':
case 'SUB':
case 'JRO':
return `${line.op} ${line.a}`
case 'MOV':
return `${line.op} ${line.a}, ${line.b}`
}
I find it cumbersome that I have to list out all possible options in order for the cases to understand if the op is a UnaryOp
or a BinaryOp
. Is there a more concise way to handle this?
IMPORTANT. Keep in mind that this is just a simplified sample, and there may be different types of Op
's in actual scenarios.