-
Notifications
You must be signed in to change notification settings - Fork 13.2k
Description
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