我正在尝试创建具有不同参数类型的函数类型的联合,但是在联合类型中,参数变为“从不”。我可以使用联合类型作为参数并获取所需的结果,也可以使用函数重载,但是为什么不允许使用函数类型联合。这是代码示例:
type FnA = (arg: 'a') => any;
type FnB = (arg: 'b') => any;
type Fn = FnA | FnB;
declare const fn: Fn;
fn('a'); // Argument of type 'string' is not assignable to parameter of type 'never'
是错误还是可以按预期工作?
它的目的是。但是,要进行重载,应该使用交集&
而不是union |
。
这是工作代码:
type FnA = (arg: 'a') => any;
type FnB = (arg: 'b') => any;
type Fn = FnA & FnB;
declare const fn: Fn;
fn('a'); // ok
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句