簡體   English   中英

將typescript ReturnType與keyof和通用類型的迭代鍵一起使用

[英]Using typescript ReturnType with keyof and iterated keys of generic type

我試圖遍歷對象中的函數並獲取它們的返回類型以進行一些過濾,如下所示:

 export const StorageActions = {
      addFile: () => ({ type: 'ADD_FILE' }),
      deleteFile: () => {
        return () => {
          return null;
        };
      },
    };

type StorageActionsTypes = typeof StorageActions;

type ValidFunctions<T> = Pick<T, {
  [K in keyof T]: ReturnType<T[K]> extends { type: any } ? K : never;
}[keyof T]>;

type functions = ValidFunctions<StorageActionsTypes>;

上面的代碼將顯示以下錯誤:

類型'T [K]'不滿足約束'(... args:any [])=> any'。

在此處輸入圖片說明

如錯誤所述,ReturnType需要一個函數,對嗎? 還是我在這里想念東西?

如何告訴ReturnType我正在傳遞函數?

您需要指定約束,即ValidFunctionsT值只能是函數:

type ValidFunctions<T extends { [key: string]: (...args: any[]) => any }> = ...

暫無
暫無

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

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