functionsum(a: number, b: number): number; functionsum(a: string, b: string): string; functionsum(a: number | string, b: number | string): number | string { if (typeof a === 'number' && typeof b === 'number') { return a + b; } return`${parseInt(a + '', 10) + parseInt(b + '', 10)}`; }
const result = sum('1000', 337);
Fixed Code ✔️
There are only two function overloads for sum. The first overload expects a and b to be of type number. The second overload expects a and b to be of type string but there is no overload that specifies a to be a string while b is a number. We have to add a third overload to allow such function calls:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Function Overload Signature 1 functionsum(a: number, b: number): number; // Function Overload Signature 2 functionsum(a: string, b: string): string; // Function Overload Signature 3 functionsum(a: string, b: number): string; functionsum(a: number | string, b: number | string): number | string { if (typeof a === 'number' && typeof b === 'number') { return a + b; } return`${parseInt(a + '', 10) + parseInt(b + '', 10)}`; }
const result = sum('1000', 337);
An even easier solution would be to remove all function overloads as the function body allows us to use number or string through the union type of number | string:
1 2 3 4 5 6 7 8
functionsum(a: number | string, b: number | string): number | string { if (typeof a === 'number' && typeof b === 'number') { return a + b; } return`${parseInt(a + '', 10) + parseInt(b + '', 10)}`; }