Search code examples
typescripttypestuplesvariadic-functionsoptional-parameters

Optional function parameter in tuple after variadic


I'm stuck with this simple problem:

declare function Foo<T extends string[]>(...s: [...T, number?]): void;

Foo("");
/* error: Argument of type '""' is not assignable to parameter of type 'number | undefined'.(2345) */

Foo(1); // ok

Foo("", 1); // ok

Why the first function call do not work while the last tuple element is optional? I tried to solve this also with signature overload but no success either.


Solution

  • I'm not quite sure why the current version doesn't work correctly. It will actually allow you to pass in an empty string, as long as you don't rely on inference:

    Foo<[""]>("");
    

    But that's obviously a bit cumbersome, so I understand why it may not be desirable

    Playground link

    The following type may work for you; it works for the cases you provided, and i havn't found any where it misbehaves:

    declare function Foo<T extends string[]>(...s: [...T] | [...T, number]): void;
    

    Playground link