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,已修复:)