代码之家  ›  专栏  ›  技术社区  ›  TomáÅ¡ Hübelbauer

TypeScript映射的类型更改值函数的返回类型

  •  0
  • TomáÅ¡ Hübelbauer  · 技术社区  · 5 年前

    我有一个这样的类型脚本:

    type Api = {
      createItem: (name: string) => Promise<Item>;
      getItem: (id: number) => Promise<Item>;
      updateItem: (item: Item) => Promise<Item>;
      deleteItem: (id: number) => Promise<void>;
    };
    

    我正试图找出如何将其转换为以下内容:

    type Api = {
      createItem: (name: string) => { type: 'success'; result: Item; } | { type: 'error' };
      getItem: (id: number) => { type: 'success'; result: Item; } | { type: 'error' };
      updateItem: (item: Item) => { type: 'success'; result: Item; } | { type: 'error' };
      deleteItem: (id: number) => { type: 'success' } | { type: 'error' };
    };
    

    我认为映射类型是一种方法:

    type NewApi = {
      [_ in keyof Api]: (???) => { type: 'success'; result: ??? } | { type: 'error' }
    };
    

    不过,我不知道如何填补那里的空白。我甚至不确定是否有可能做到这一点。

    我需要此类型的原因是,我正在构建网关代理,而该类型的实际实现将是 Proxy 对象拦截成员访问,并使用另一个代理模拟其值,该代理将捕获函数调用以进行更改,并返回上述联合类型。

    实现部分很好,但我似乎无法获取使Intellisense工作的类型。

    1 回复  |  直到 5 年前
        1
  •  3
  •   zhuber    5 年前

    您可以使用类型脚本 Parameters ReturnType 类型

    type NewApi = {
      [K in keyof Api]: (...args: Parameters<Api[K]>) => { type: 'success'; result: ReturnType<Api[K]> } | { type: 'error' }
    };
    

    请看这个 playground .