代码之家  ›  专栏  ›  技术社区  ›  jeanpaul62

返回函数类型的TypeScript接口

  •  1
  • jeanpaul62  · 技术社区  · 7 年前

    假设我有5个咖喱函数,第一个是 Api 对象,作为api调用本身的第二个(可选)参数。

    // functions.ts
    function f1 (api: Api) {
      return () => { // returns a Promise<string> }
    }
    
    // some other functions
    
    function f5 (api: Api) {
      return (id: number) => { // returns a Promise<number> }
    }
    

    {
      f1: () => Promise<string>
      // ...
      f5: (id: number) => Promise<number>
    }
    

    以下是我所做的:

    import * as functions from './functions';
    
    const api = new Api(); // Define the Api object here
    
    const withApi = Object.keys(functions).reduce((result, key) => {
      result[key as keyof typeof functions] = functions[key as keyof typeof functions](api)
    }, {} as /* What type should i put here??? */);
    

    我能找到的最好的 /* What type should i put here??? */ { [index:string]: Promise<any> } ,这一点都不令人满意。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Titian Cernicova-Dragomir    7 年前

    您可以创建一个映射类型,该类型将包含原始函数对象中所有键的键,但它们的类型将与每个函数的返回类型相同(使用条件类型提取) ReturnType<T>

    type AllReturnTypes<T extends Record<keyof T, (...a: any) => any>> = {
        [P in keyof T]: ReturnType<T[P]>
    }
    const withApi = Object.keys(functions).reduce((result, key) => {
        result[key as keyof typeof functions] = functions[key as keyof typeof functions](api)
        return result;
    }, {} as AllReturnTypes<typeof functions>);
    
    withApi.f1();
    withApi.f5(10);
    
    推荐文章