首页 > 解决方案 > 不能用函数类型的联合重载函数

问题描述

我正在尝试创建具有不同参数类型的函数类型的联合,但在联合类型中,参数变为“从不”。我可以使用联合类型作为参数并获得我需要的结果,或者使用函数重载,但是为什么不允许函数类型的联合。这是代码示例:

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'

是错误还是按预期工作?

标签: typescript

解决方案


它的目的是。但是,要进行重载,您应该使用交集&而不是 union |

这是工作代码:

type FnA = (arg: 'a') => any;
type FnB = (arg: 'b') => any;
type Fn = FnA & FnB;
declare const fn: Fn;
fn('a'); //  ok

推荐阅读