简体   繁体   中英

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 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM