簡體   English   中英

從打字稿中的功能參數推斷類型參數

[英]infer type argument from function argument in typescript

我有這個游樂場和這個代碼

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>

我認為目前尚無法直接實現,因為對泛型沒有部分推斷,請參見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,這有助於將他們推向正確的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM