TypeScript: Varargs Overload Signatures

Nicholas Jamieson
3 min readDec 3, 2020
Photo by Matt Artz on Unsplash

I thought I’d write up a short post to explain a TypeScript problem that took up far too much of my time.

The TL;DR is that if you have overload signatures for a function that takes a variable number of (initial) arguments, the ordering of the signatures matters in a way that is not obvious. And the ‘simplest’ signature should be placed first.

The types I was working with were in RxJS, but to keep things general let’s use an example that combines a bunch of arrays in some way, like this:

alt (github.com)

The combine function will take elements from each of the input arrays that are passed — the caller can pass as many as is necessary — and will return an array containing the combined elements. (How they are combined doesn’t matter; we’re only interested in the types.)

combine could be typed like this:

alt (github.com)

Without going into too much detail, Inputs is mapped type that maps a tuple of element types to a tuple of read-only arrays — for the input array parameters — like this:

alt (github.com)

And the element type of the returned array is obtained — from the Elements type parameter — using this mechanism:

alt (github.com)

With the signature declared like this, the return value’s type is inferred correctly:

alt (github.com)

Let’s say the combine function can also be passed a count to specify how many elements at a time should be taken from each input array. We can add an overload signature like this:

--

--

Nicholas Jamieson

RxJS core team member; front-end developer; mentor; speaker; open-source contributor