简体   繁体   English

打字稿:用其余参数组装一个联合?

[英]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我希望union应该有一个 union type string | number string | number , but instead U is set to the type of the first argument ( string ). string | number ,但U被设置为第一个参数的类型( 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 }) ).我不确定围绕此的设计决策,但是如果您有U[] ,编译器将不会推断出联合,它至少会为原语发出错误(例如,这会导致联合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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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