Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript:用rest参数组装一个并集?_Typescript_Typescript Typings - Fatal编程技术网

Typescript:用rest参数组装一个并集?

Typescript:用rest参数组装一个并集?,typescript,typescript-typings,Typescript,Typescript Typings,参见代码: 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' type FN=(…rest:U[])=>U 声明常数fn:fn let union=fn('bar',123)//类型为'123'的参数不能分配给类型为

参见代码:

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'
type FN=(…rest:U[])=>U
声明常数fn:fn
let union=fn('bar',123)//类型为'123'的参数不能分配给类型为'string'的参数
我希望
union
应该有一个union类型
string | number
,但是
U
被设置为第一个参数的类型(
string

是否可以将rest参数类型推送到联合体


我不确定这方面的设计决策,但是如果您有
U[]
编译器不会因此推断联合,它至少会对原语发出错误(例如,这会导致联合
let union=fn({a:'bar'},{b:123})

一个简单的解决方法是在rest参数中使用元组:

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

declare const fn: FN

let union = fn('bar', 123) // string | number
type FN=(…rest:U)=>U[number]
声明常数fn:fn
让union=fn('bar',123)//字符串|编号

我认为您的游乐场链接包含其他内容。@TitianCernicova Dragomir 10x,已修复:)