Nurbol Alpysbayev
Nurbol Alpysbayev

Reputation: 21851

Typescript: assemble a union out of rest parameters?

See the code:

type FN = <U>(...rest: U[]) => U

declare const fn: FN

let union = fn('bar', 123) // Argument of type '123' is not assignable to parameter of type 'string'

I expected that union should have a union type string | number, but instead U is set to the type of the first argument (string).

Is it possible to push types of rest arguments to a union?

Playground

Upvotes: 3

Views: 284

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249506

I am not sure of the design decisions around this, but if you have U[] the compiler will not infer a union for that it will rather issue an error for primitives at least (this for example results in a union let union = fn({ a: 'bar' }, { b: 123 })).

A simple workaround is to use tuples in rest parameters instead:

type FN = <U extends any[]>(...rest: U) => U[number]

declare const fn: FN

let union = fn('bar', 123) // string | number

Upvotes: 1

Related Questions