typescript重载的Variadic泛型函数隐式具有“ any”类型的问题

问题描述 投票:0回答:1

这里是代码片段

export type actions = {
  abort: () => void;
  back: () => void;
  next: () => void;
  resume: () => void;
};

class Sabar {
  public use<T1>(fn: (arg1: T1, ctx: object, actions: actions) => void) :void;
  public use<T1, T2>(fn: (arg1: T1, arg2: T2, ctx: object, actions: actions) => void) :void;
  public use<T1, T2, T3>(fn: (arg1: T1, arg2: T2, arg3: T3, ctx: object, actions: actions) => void) :void;
  public use<T1, T2, T3, T4>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, ctx: object, actions: actions) => void) :void;
  public use(fn: Function) :void {
    // ....
  }
}

const test = new Sabar();

test.use((first, second, third) => {}) // indicate `second` is object, `third` is actions
test.use((first, second, third, forth) => {}); // indicate `first`, `second`, `third`, `forth` as any

use函数始终具有两个尾部参数ctxactions。标题参数具有可变长度。

问题是:

  1. [当提供具有三个参数的函数时,ts可以指示正确的类型信息。
  2. 但是,当所提供的函数具有四个,五个或更多参数时,所有这些参数都将以any类型指示。

我很长时间以来都一直在尝试搜索原因...仍然无法解决。希望有人能帮我一个忙。

谢谢..

typescript variadic-functions typescript-generics
1个回答
0
投票

在您的示例中,Typescript编译器无法确定arg1arg2arg3arg4的类型。您必须通过明确说明模板参数来帮助编译器。例如-

test.use<string>((first, second, third) => { })
// indicate `first` as string, 
// `second` as object, 
// `third` as actions,

test.use<string, number>((first, second, third, forth) => { });
// indicate `first` as string, 
// `second` as number, 
// `third` as object,
// `forth` as actions
© www.soinside.com 2019 - 2024. All rights reserved.