首页 > 解决方案 > 从打字稿中的函数参数推断类型参数

问题描述

我有这个游乐场和这段代码

export interface RemoteMethods<R> {
  getAll: (url: string) => Promise<R>;
  create: (url: string, model: R) => Promise<void>;
}

export type AsyncFunctionReturnType<
  R,
  Method extends keyof RemoteMethods<R>
> = 
  {
    [key in Method]: RemoteMethods<R>[Method];
  };

export const makeRemoteMethods = <R>(
) => {
  return {
    getAll: async (url: string) => {
      return Promise.resolve(undefined);
    },
    create: async (url: string, model: R) => {
      return Promise.resolve(undefined);
    },
  };
};


export const useAsyncCallback = <
  R,
  K extends keyof ReturnType<typeof makeRemoteMethods>
>(
  method: K,
): AsyncFunctionReturnType<R, K> => {
  const remoteMethods = makeRemoteMethods<R>();

  const m = { [method]: remoteMethods[method] } as unknown as {
    [key in K]: RemoteMethods<R>[K];
  };

  return {
    ...m,
  };
};

const getAllSites = useAsyncCallback<{x: string}, 'getAll'>('getAll');

我想以某种方式推断此函数调用中的第二个类型参数

const getAllSites = useAsyncCallback<{x: string}, 'getAll'>('getAll');

我想调用如下函数:

const getAllSites = useAsyncCallback<{x: string}>('getAll');

并以某种方式推断类型参数K extends keyof ReturnType<typeof makeRemoteMethods>

标签: typescript

解决方案


我相信这目前不可能直接实现,因为没有对泛型的部分推断,请参阅https://github.com/microsoft/TypeScript/issues/10571https://github.com/microsoft/TypeScript/issues/20122(后者几乎是完全相同的代码)。可能有解决方法,但它们不会很好。

然而,对此的适当支持正在慢慢到来!https://github.com/microsoft/TypeScript/pull/26349是 TypeScript 的当前开放 PR,它允许您像这样调用您的函数:

const getAllSites = useAsyncCallback<{x: string}, _>('getAll');

此处_表示您希望推断的通用变量,并且需要对该 var 进行正常推断行为(就像您看到的是否只有一个通用 arg,这是自动推断的)。

这尚未确认或合并 TypeScript 的行为,但如果您希望这样做,您可以 +1 该问题和 PR,这将有助于推动他们找到正确的解决方案。


推荐阅读