这里是代码片段
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
函数始终具有两个尾部参数ctx
和actions
。标题参数具有可变长度。
问题是:
ts
可以指示正确的类型信息。any
类型指示。我很长时间以来都一直在尝试搜索原因...仍然无法解决。希望有人能帮我一个忙。
谢谢..
在您的示例中,Typescript编译器无法确定arg1
,arg2
,arg3
和arg4
的类型。您必须通过明确说明模板参数来帮助编译器。例如-
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