-
Notifications
You must be signed in to change notification settings - Fork 13.2k
Closed as not planned
Labels
DuplicateAn existing issue was already createdAn existing issue was already created
Description
π Search Terms
"function overloading", "method overloading"
β Viability Checklist
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
β Suggestion
The way TypeScript currently supports function overloading causes programmers to write lengthy and hard-to-read code (distract from the main logic of the function). Programmers have to write boilerplate code to do what the machine should do behind the scene: choose the correct function implementation based on arguments.
Therefore, TypeScript should support function overloading in a clearer syntax, like C++ or Java does.
π Motivating Example
TypeScript's old syntax for function overloading:
function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: any, b: any): any {
if (typeof a === 'number' && typeof b === 'number') { // distracting
return a + b;
} else if (typeof a === 'string' && typeof b === 'string') { // distracting
return a + b;
}
throw new Error('Invalid arguments');
}
console.log(add(10, 20)); // 30
console.log(add('Hello, ', 'world!')); // 'Hello, world!New, improved TypeScript overloading syntax:
function add(a: number, b: number): number {
return a + b;
}
function add(a: string, b: string): string {
return a + b;
}
console.log(add(10, 20)); // 30
console.log(add('Hello, ', 'world!')); // 'Hello, world!π» Use Cases
- What do you want to use this for?
- To write cleaner code whenever function/method overloading is needed
- What shortcomings exist with current approaches?
- Current TypeScript function overloading syntax requires writing boilerplate, distracting code.
- What workarounds are you using in the meantime?
- None.
Metadata
Metadata
Assignees
Labels
DuplicateAn existing issue was already createdAn existing issue was already created