Skip to content

Support proper function overloadingΒ #62893

@ghosuser706

Description

@ghosuser706

πŸ” Search Terms

"function overloading", "method overloading"

βœ… Viability Checklist

⭐ 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

  1. What do you want to use this for?
  • To write cleaner code whenever function/method overloading is needed
  1. What shortcomings exist with current approaches?
  • Current TypeScript function overloading syntax requires writing boilerplate, distracting code.
  1. What workarounds are you using in the meantime?
  • None.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions