Optional Rest Parameter Overloading in TypeScript

Posted on 2021-02-04 21:13:05+00:00

You have a function with different return types based on whether or not rest parameters are passed in. Maybe it's a fringe edge case, but you never know when you'll need it. Read on to find a way to statically type this use case.

First, we have our use case without rest parameters:

1
function overloaded(foo: number): number;

Now we want our version with rest parameters to return something else:

1
function overloaded(foo: number, ...objects: string[]): boolean;

We can't have optional rest parameters in the first case, so the trick is to pass in an empty tuple, like so:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
function overloaded(foo: number, ...objects: []): number;
function overloaded(foo: number, ...objects: string[]): boolean;
function overloaded(foo: number, ...objects: [] | string[]): number | boolean {
    if (objects.length == 0) {
        return 1;
    }

    return true;
}

const value1 = overloaded(5) // Type will be number.
const value2 = overloaded(5, "a", "b", "c") // Type will be boolean.

And that's it. You're done, with static typing through and through.

Learning TypeScript? Subscribe to my TypeScript articles, tips and tutorials.

Comments

Alvaro Gutierrez2021-06-05 21:16:27.200503+00:00

not sure about line 12

Reply

Post New Comment

We will not expose this.