T
T
toly192019-05-17 21:39:15
JavaScript
toly19, 2019-05-17 21:39:15

How to declare an argument with an array of functions and promises?

I can't figure out how to declare a function argument, which is an array of functions, each of which returns a promise. Here is my attempt at the declaration (doesn't work)

function anyFunc(inputFunctions: (<T>() => Promise<T>)[]) {
    return Promise.all(inputFunctions.map(value => value()));
}

use like this:
anyFunc([() => Promise.resolve(1), () => Promise.resolve("a")]).then(value => {
    console.log(value); //[1, "a"]
});

that is, in the end, ts should know what kind of values ​​are in value
, the error itself:
Type 'Promise<string>' is not assignable to type 'Promise<T>'.
  Type 'string' is not assignable to type 'T'.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
forspamonly2, 2019-05-18
@toly19

type PromiseCallResults<T> = {
  [P in keyof T]: T[P] extends (() => Promise<infer R>) ? R : never;
}

function anyFunc<T extends (()=>Promise<unknown>)[]>(...inputFunctions: T) {
  return Promise.all(inputFunctions.map(value => value())) as Promise<PromiseCallResults<T>>;
}

anyFunc(() => Promise.resolve(1), () => Promise.resolve("a")).then(value => {
  console.log(value); //[1, "a"]

  const checktypes:[number, string] = value;
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question