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

Typescript获取类型“import*as whatIsMyType from'./foo';”

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

    我的 foo.ts 导出具有相同签名的多个函数,例如。 (a: number): number .

    在我的主要技术支持是的,我知道

    import * as foo from './foo';
    // foo.myFunction1 and foo.myFunction2 are defined
    
    export const resultsFor = (a: number) => {
      return Object.keys(foo).reduce(
          (result, currentKey) => {
            result[currentKey] = foo[currentKey](a);
            return result;
          },
          {} as {[index:string]: number}
        );
    }
    

    现在是 resultFor (a: number): {[index:string]: number} ,但这有点过于笼统。

    我希望 结果

    (a: number): {myFunction1: number, myFunction2: number, /* and other exports from 'foo.ts': number */}
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Cerberus    7 年前

    可以使用映射类型和 keyof . 考虑以下几点:

    type fooKey = keyof typeof foo;
    export const resultsFor = (a: number) => {
        return Object.keys(foo).reduce(
            (result, currentKey) => {
                result[currentKey as fooKey] = foo[currentKey as fooKey](a);
                return result;
            },
            {} as {[index in fooKey]: number}
        );
    }
    

    这里,我们使用显式类型断言,因为我们知道 Object.keys

    推荐文章