【问题标题】:Typescript - Define interface for a very general function [duplicate]Typescript - 为非常通用的功能定义接口[重复]
【发布时间】:2020-09-24 17:29:03
【问题描述】:

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

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

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

如何在不使用any 的情况下定义这样的函数参数?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    我向您推荐以下内容,这将允许您拥有返回数据的类型:

    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

    【讨论】:

      【解决方案2】:

      如果这种类型非常灵活,您将始终以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();
      }
      

      希望对你有帮助。

      【讨论】:

        【解决方案3】:

        使用这个:

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

        【讨论】:

          【解决方案4】:

          你可以这样定义:

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

          希望这会有所帮助。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-01-12
            • 2019-10-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-01-10
            • 2019-10-11
            • 1970-01-01
            相关资源
            最近更新 更多