Skip to content

Suggestion: Compile time function overloading #3442

Closed

Description

As we know JavaScript doesn't support overloaded functions, it's when a few functions with different signatures share the same name within the same scope where they are defined. Overloading can still be achieved at runtime by checking arguments and dispatching the execution to a proper path.

TypeScript seems capable of doing static function overloading which can be resolved at the compile time. Here is one way of how it can be done:

  • a notion of a nominal and effective name of a function is required
  • a nominal name is an identifier which is used to name a function and reference it in the TypeScript code
  • an effective name is an identifier which is used to name a function and reference it in the JavaScript code
  • an effective name is optional, if omitted then the effective name should be the same as the nominal name
  • a nominal name is a subject for overloading and hence can be shared across more than one function within the same scope
  • an effective name has to be unique withing the scope
  • the developer is in charge for specifying both nominal and effective names
  • the TypeScript emitter should only use the effective names for generating the JavaScript code
  • a resolution of a nominal name to an effective name should be based on the signature information
  • the hypothetical syntax (TBD) for a function declaration utilizing both the effective and nominal name might look like the following:
function nominalName:effectiveName() : void {
}

Example:

// typescript

function format:formatNumber(value: number) : string {
     return number.toFixed(2);
}

funciton format:formatDate(value: Date): string {
    return date.toIsoString();
}

var when = format(new Date());
var howMuch = format(999.99);
/// generated javascript

function formatNumber(value: number) : string {
     return number.toFixed(2);
}

funciton formatDate(value: Date): string {
    return date.toIsoString();
}

var when = formatNumber(new Date());
var howMuch = formatDate(999.99);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    Out of ScopeThis idea sits outside of the TypeScript language design constraintsSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions