typescript - 不能用函数类型的联合重载函数
问题描述
我正在尝试创建具有不同参数类型的函数类型的联合,但在联合类型中,参数变为“从不”。我可以使用联合类型作为参数并获得我需要的结果,或者使用函数重载,但是为什么不允许函数类型的联合。这是代码示例:
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
推荐阅读
- javascript - 如何防止 iOS Safari 上的过度滚动?
- java - 当我在服务器上执行我的代码时,方法 sendKeys(Keys.ARROW_DOWN) 不起作用
- python - 如何将python中的类转换为pandas数据框?
- c# - Wpf-Application 在 Windows 10 上看起来不同
- javascript - 为什么错误对象的消息和堆栈属性不可枚举
- python - 在python中按一定顺序排列任务
- javascript - Ramda GroupBy - 如何按任何道具分组
- reactjs - React - 动态创建选择所有复选框
- deck.gl - 如何在 react-map-gl/deck.gl 视口上获得 H3 六边形?
- mysql - 如何选择具有空值的列并使用该列的 id 选择另一个表的另一列