export function operator(a: number, b: number, operator: string, type: string): string | number {    switch (operator) {        case 'add':            if (type == answer) {                return a + b;            } else if (type == assignment) {                return a.toString() +  +  + b.toString();            }        case 'sub':            if (type == answer) {                return a - b;            } else if (type == assignment) {                return a.toString() +  -  + b.toString();            }    }}How to avoid code duplication in a Typescript switch?Attemptif (operator == 'add' && type == answer) {    return a + b;} else if (operator == 'add' && type == assignment) {    return a.toString() +  +  + b.toString();} else if (operator == 'sub' && type == answer) {    return a - b;} else if (operator == 'sub' && type == assignment) {    return a.toString() +  -  + b.toString();}
How to avoid duplicate if-else statements within a Typescript switch?
typescript
You can use conditional/ternary operatorreturn type === 'assignment' ? a + ' + ' + b : a + b;toString() when working with strings, work as string concatenation operator and operands will be implicitly casted to string. Thus, toString() in else is not required.Note that, the code is not equivalent to if...else if..., this is if...else code and is equivalent toif (type === 'assignment') {    return a + ' + ' + b;} else {    return a + b;}