TS2769

error TS2769: No overload matches this call.

Broken Code ❌

1
2
3
4
5
6
7
8
9
10
function sum(a: number, b: number): number;
function sum(a: string, b: string): string;
function sum(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
function sum(a: number, b: number): number;
// Function Overload Signature 2
function sum(a: string, b: string): string;
// Function Overload Signature 3
function sum(a: string, b: number): string;
function sum(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
function sum(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);