简体   繁体   English

将typescript ReturnType与keyof和通用类型的迭代键一起使用

[英]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'. 类型'T [K]'不满足约束'(... args:any [])=> any'。

在此处输入图片说明

As error described, ReturnType expects a function, is that correct? 如错误所述,ReturnType需要一个函数,对吗? or am I missing something here? 还是我在这里想念东西?

how can I tell the ReturnType that I am passing a function? 如何告诉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