Many inquiries revolve around the workings of function overloading in Typescript, such as this discussion on Stack Overflow. However, one question that seems to be missing is 'why does it operate in this particular manner?' The current implementation of function overloading looks something like this:
function foo(param1: number): void;
function foo(param1: number, param2: string): void;
function foo(...args: any[]): void {
if (args.length === 1 && typeof args[0] === 'number') {
// implementation 1
} else if (args.length === 2 && typeof args[0] === 'number' && typeof args[1] === 'string') {
// implementation 2
} else {
// error: unknown signature
}
}
In essence, Typescript was designed to simplify a programmer's life by incorporating syntactic sugar for Object-Oriented Design. So why isn't Typescript handling this complexity itself instead of burdening the programmer? A more convenient approach could resemble this:
function foo(param1: number): void {
// implementation 1
};
function foo(param1: number, param2: string): void {
// implementation 2
};
foo(someNumber); // result 1
foo(someNumber, someString); // result 2
foo(someNumber, someNumber); // ts compiler error
This hypothetical Typescript code would then be transpiled into the equivalent Javascript representation:
function foo_1(param1) {
// implementation 1
};
function foo_2(param1, param2) {
// implementation 2
};
function foo(args) {
if (args.length === 1 && typeof args[0] === 'number') {
foo_1(args);
} else if (args.length === 2 && typeof args[0] === 'number' && typeof args[1] === 'string') {
foo_2(args);
} else {
throw new Error('Invalid signature');
}
};
The lack of a clear rationale behind why Typescript doesn't follow this simplified structure leaves room for speculation. Any thoughts on this matter?