question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Suggestion: Automatically infer argument types in overloaded function implementation

See original GitHub issue

Search Terms

infer, arguments, function, overload

Suggestion

For basic container types (Point, Size, Rect, …) I often write constructors and methods with overloaded signatures so they can be called with the container type itself or with the separate components of the container as arguments. Example:

class Point {
    constructor(point: Point);
    constructor(x: number, y: number);
    constructor(arg1: Point | number, arg2?: number) {
        if (arg1 instanceof Point) {
            this.x = arg1.getX();
            this.y = arg1.getY();
        } else {
            this.x = arg1;
            this.y = arg2!;
        }
    }
}

And I always wonder why I have to specify the argument types in the implementation again when I already defined the possible types in the overload signatures.

In this simple Point type it is still pretty easy but imagine a Rect type which can work with four number arguments, two Point arguments, a Point and Size argument or a Rect argument. Manually writing the combined signature for all these overloaded signatures is cumbersome. And I don’t want to use any here because I want type checking in the function body.

An alternative way to write this example is this:

class Point {
    constructor(point: Point);
    constructor(x: number, y: number);
    constructor(...args: [ Point ] | [ number, number ]) {
        const [ arg1, arg2 ] = args;
        // arg1 is now Point | number
        // arg2 is now number | undefined (At least since TS 3.2 because of #27543)
        ...
    }
}

This shows how easy it should be for TypeScript to collect the possible function signatures into a union type so writing constructor(...args) would be enough.

Taking this a step further I even like to write this so I don’t need to destructure the arguments myself:

class Point {
    constructor(point: Point);
    constructor(x: number, y: number);
    constructor(arg1, arg2) {
        // arg1 is now Point | number
        // arg2 is now number | undefined
        ...
    }
}

Taking this ANOTHER step further TypeScript could even narrow down the inferred function signatures by each type check done within the function body:

class Point {
    constructor(point: Point);
    constructor(x: number, y: number);
    constructor(arg1, arg2) {
        if (arg1 instanceof Point) {
            // arg2 can now only be `undefined` because the instanceof check removes 
            // the second call signature (where arg1 is a number) from the list of possible 
            // call signatures
            this.x = arg1.getX();
            this.y = arg1.getY();
        } else {
            // arg2 can now only be `number` because the failed instanceof check removes 
            // the first call signature from the list of possible signatures
            this.x = arg1;
            this.y = arg2;
        }
    }
}

I guess the type narrowing is harder to implement but at least the automatic type inference of each argument shouldn’t be that hard. So it would be very nice if a future version of TypeScript could do this so using overloading gets a bit easier.

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. new expression-level syntax)

Issue Analytics

  • State:open
  • Created 5 years ago
  • Reactions:22
  • Comments:9 (2 by maintainers)

github_iconTop GitHub Comments

3reactions
daprahamiancommented, Feb 1, 2021

This feature would be pretty valuable when dealing with node-style callback:

function checkNumber(x: number): void {}
function checkUndefined(x: undefined): void {}

function callback(err: number, val: undefined): void;
function callback(err: undefined, val: number): void;
function callback(err: number|undefined, val: number|undefined): void {
    if (err == null) {
        checkUndefined(err);
        checkNumber(val); // would like to be able to infer that this is a number
    } else {
        checkUndefined(val); // would like to infer that this is undefined
        checkNumber(err)
    }
}

1reaction
Jamesernatorcommented, Mar 1, 2022

So TS4.4 added control flow analysis on discriminants, I wonder if that support could be extended to tuples such that inferred types after narrowing.

So TS4.6 just added a limited version of this in way of inference of args for discriminated tuples. Hopefully we will see support for more generic signatures in future.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Why does an overloaded function declaration sometimes ...
I don't understand why I get an error if a constraint generic type parameter is used directly in the function implementation instead of...
Read more >
More types - mypy 0.991 documentation
An overloaded function must consist of two or more overload variants followed by an implementation. The variants and the implementations must be adjacent...
Read more >
Function Overloading
Overloaded functions enable you to supply different semantics for a function, depending on the types and number of its arguments.
Read more >
Frequently Asked Questions (FAQ)
... and not a method? Why does Go not support overloading of methods and operators? ... Why can't the compiler infer the type...
Read more >
Boost: bind.hpp documentation - 1.46.0
Why doesn't bind automatically recognize nonstandard functions? ... be specified explicitly (without a typeof operator the return type cannot be inferred):
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found