Take the following minimal 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 }
And the following "pattern match":
switch (line.op) {
case 'ADD':
case 'SUB':
case 'JRO':
return `${line.op} ${line.a}`
case 'MOV':
return `${line.op} ${line.a}, ${line.b}`
}
I don't particularly like that, in order for the case to understand the op is a UnaryOp
or a BinaryOp
, I have to enumerate all the possibilities. Is there a compact(er) way to achieve this?
NOTE. Take into consideration that this is a simplified example, and there might be other kind of Op
's.