我正在尝试创建具有不同参数类型的函数类型的联合,但在联合类型中,参数变为“从不”。我可以使用联合类型作为参数并获得我需要的结果,或者使用函数重载,但为什么不允许函数类型的联合。下面是代码示例:
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'
Run Code Online (Sandbox Code Playgroud)
是错误还是按预期工作?
它的目的是。但是,要进行重载,您应该使用 intersection&而不是 union |。
这是工作代码:
type FnA = (arg: 'a') => any;
type FnB = (arg: 'b') => any;
type Fn = FnA & FnB;
declare const fn: Fn;
fn('a'); // ok
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31 次 |
| 最近记录: |