Typescript:使用函数数组的 ReturnType(已编辑)

标签 typescript typescript-typings typescript-generics

我正在尝试输入以下函数:

function foo(input, modifier, merge) {
    return merge(...modifier.map(m => m(input)));
}

目标是为 merge 的参数设置正确的类型功能。

上下文:

  • modifier是一个函数数组,带有一个 typeof input 类型的参数以及每个函数的不同返回类型
  • merge是一个函数,它有 modifier.length参数,位置 n 的参数与函数的返回类型具有相同的类型 modifier[n]并返回一个(通用)值

如何做到这一点?


编辑:备选问题

可能与对象 ( Record<K,V> ):

// for Functions (here type Func)
type Func = () => any;

// a mapping of a string key to an function can be created
type FuncMap = Record<string, Func>;

// for this mapping you can create a mapping to the return types of each function
type ReturnTypeMap<T extends FuncMap> = { [K in keyof T]: ReturnType<T[K]> }

基于位置而不是对象键,数组也可以这样吗?


这是我尝试键入函数,但我不知道如何将 ReturnType 与数组结合使用:

function foo<I, M extends Array<(input: I) => any>, O>(
    input: I,
    modifier: M,
    merge: (...args: ReturnType<M>) => O
    //               ^^^^^^^^^^^^^ this is not working, since relation to each item is missing
): O {
    return merge(...modifier.map(m => m(input)));
}

最佳答案

我认为这样做:

type ExtractReturnTypes<T extends readonly ((i: any) => any)[]> = [
  ... {
    [K in keyof T]: T[K] extends ((i: any) => infer R) ? R : never
  }
];

function foo<I, M extends readonly ((i: I) => any)[], O>(
  input: I,
  modifiers: M,
  merge: (...args: ExtractReturnTypes<M>) => O
) {}

foo(
  1,
  [(i: number) => 5, (i: number) => 'b' as const] as const,
  // a has type: number
  // b has type: 'b'
  (a, b) => 'test'
);

关于Typescript:使用函数数组的 ReturnType(已编辑),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65038381/

相关文章:

TypeScript Watch - 删除已删除的目标 JS 文件

javascript - 在 Angular 6 中显示来自 api 的数据时出现问题

javascript - 如何衡量 promise 的执行时间?

javascript - 字符串变量值作为类型中的属性

typescript - Typescript 类型定义中 Jasmine 的重复签名

typescript - 如何从联合类型在 TypeScript 中创建 Promise

angularjs - 更新模型时 Angular 2 中的双向绑定(bind)

typescript - ionic 2 : How to fix usage of moment. js 错误

typescript - 如何从 TypeScript 中的枚举值构建类型?

带有元组类型联合的 typescript 类型推断