Skip to content

Check overloaded function implementation for every overload signatureΒ #52478

@Amareis

Description

@Amareis

Suggestion

πŸ” Search Terms

overload, overloaded function, overloaded implementation

βœ… Viability Checklist

My suggestion meets these guidelines:

  • 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 feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

Initially discussed in #33912.

For overloaded function implementation its body could be checked with every overload signature. Effectively, it's just normalized overload signature (so arguments count is same for every overload, but some of them is just undefined) + implementation source code. If type checking for any of this enriched overloads is failing, implementation is incorrect.

πŸ“ƒ Motivating Example

Before:

function fun(a: string): number
function fun(a: number): string
function fun(a: string | number): number | string {
    return a //totally incorrect
}

After:

function fun(a: string): number
function fun(a: number): string
function fun(a /*:infer*/)/*:infer*/ {
    //TSXXXX: string is not assignable to number for overload (a: string) => number
    //TSXXXX: number is not assignable to string for overload (a: number) => string
    return a 

πŸ’» Use Cases

Obviously, this will be good for every overloaded functions/methods, but checking will be somewhat slower.
For backward compatibility additional syntax (e.g. infer in function argument/return type position) or compiler flag may be required.
Handles many cases for #33912

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