gpt4 book ai didi

typescript - 无法使用函数类型的联合重载函数

转载 作者:行者123 更新时间:2023-12-02 18:58:32 26 4
gpt4 key购买 nike

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

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'

这是一个错误还是它按预期工作?

最佳答案

这是故意的。但是,要进行重载,您应该使用交集 & 而不是并集 |

这是工作代码:

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

关于typescript - 无法使用函数类型的联合重载函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65897736/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com