Typescript-为非常通用的功能定义接口

时间:2020-06-05 13:30:27

标签: typescript

我提供了一个函数functionCaller的示例。它需要一个函数,任何类型的函数。

const functionCaller = (func: any /* how to define this general func? */) => {
  func();
};

functionCaller((hello: string) => {});
functionCaller(() => {});
functionCaller(() => new Promise((resolve) => {}));

如何不借助any来定义这样的函数参数?

4 个答案:

答案 0 :(得分:1)

如果这种类型是灵活的,您将始终以any结尾。

但是,函数类型将是这样

type AnyFunction = (...args: any[]) => any;

const functionCaller = (func: AnyFunction) => {
    func();
}

或者,通过进行泛型类型可以更精确。

type Args = any[] | never;
type AnyFunction<TArgs extends Args, TResult> = (...args: TArgs) => TResult;

const functionCaller = <TResult>(func: AnyFunction<any[], TResult>) => {
    func();
}

希望有帮助。

答案 1 :(得分:0)

使用此:

const functionCaller = (func: Function) => {
  func();
};

答案 2 :(得分:0)

我建议您执行以下操作,以使您拥有返回数据的类型:

function functionCaller<T extends (...args: any[]) => any>(func: T): ReturnType<T> {
    return func();
}

const funcA = (hello: string) => { };
const funcB = () => { };
const funcC = () => new Promise((resolve) => { })

const typeA = functionCaller<typeof funcA>(funcA);

const typeB = functionCaller<typeof funcB>(funcB);

const typeC = functionCaller<typeof funcC>(funcC);

playground

答案 3 :(得分:-1)

您可以这样定义它:

const functionCaller = (func: () => any) => {
  func();
};

希望这会有所帮助。