简体   繁体   中英

Using typescript ReturnType with keyof and iterated keys of generic type

I am trying to loop through functions in an object and get their return type to do some filtering as follow:

 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>;

the above code will show the following error:

Type 'T[K]' does not satisfy the constraint '(...args: any[]) => any'.

在此处输入图片说明

As error described, ReturnType expects a function, is that correct? or am I missing something here?

how can I tell the ReturnType that I am passing a function?

您需要指定约束,即ValidFunctionsT值只能是函数:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM