cyrus-d
cyrus-d

Reputation: 843

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'.

enter image description here

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?

Upvotes: 2

Views: 1024

Answers (1)

Dmitriy
Dmitriy

Reputation: 2822

You need to specify constraint that values of T inside ValidFunctions only can be functions:

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

Upvotes: 3

Related Questions