简体   繁体   English

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

[英]Typescript: use ReturnType of array of functions (edited)

I am trying to type the following function:我正在尝试输入以下 function:

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

The objective is to have the correct types for the parameters of the merge function.目标是为merge function 的参数提供正确的类型。

Context:语境:

  • modifier is an array of function with a single parameter of the type of typeof input and a different return type for each function modifier是 function 的数组,具有typeof input类型的单个参数和每个 function 的不同返回类型
  • merge is a function, which has modifier.length parameters, with the parameter at position n having the same type as the return type of the function modifier[n] and returns a singe (generic) value merge是一个function,它有modifier.length参数,在position n处的参数与function的返回类型具有相同的类型)值modifier[n]

How can this be done?如何才能做到这一点?


Edit: Alternative Question编辑:替代问题

Possible with objects ( Record<K,V> ):可以使用对象( 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]> }

Is something like this also possible for arrays, based on the position instead of a object key?基于 position 而不是 object 密钥的 arrays 是否也可以进行类似的操作?


This is my attempt at the typing the function, but i don't know how to use ReturnType in combination with arrays:这是我尝试输入 function,但我不知道如何将 ReturnType 与 arrays 结合使用:

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

Do it like this I think:这样做我认为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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