0

I have the following code :


function builder<T extends Foo>(
  getItems: (...) => Promise<T[]>, /* unsure what to put between parenthesis here */
) {
  return async (...): Promise<Baz> => { 
    const items = await getItems(...); /* unsure what to put between parenthesis here */
    // some manipulation here
    return items;
}

My goal is to allow the builder function to accept an asynchronous callback. This callback can be called with various types of parameters. There could be one, or many parameters inside the callback.

For example, I could call the builder function such as :

// call 1 
builder<SomeResult>((a, b) => someCallback(a, b));

// call 2
builder<AnotherResult>((c) => otherCallback(c)); 

I'm pretty new to typescript so not quite sure how to do this. I think maybe i should look into rest arguments but not exactly sure how to tackle the problem.

Any help would be much appreciated. Thanks a lot for the tips.

7
  • When the function you pass can take multiple arguments, where do those arguments come from? You can't just produce them out of nowhere. Commented Nov 16, 2020 at 0:57
  • Agreed, but my point was, those arguments (a, b, c) could be of any type. For example a could be a date, b could be a number, c could be a boolean. In the builder i just want to be able to call getItems with whatever arguments were passed via the callback. Commented Nov 16, 2020 at 1:01
  • ...but the arguments passed to the callback are the arguments that you call getItems with, so how would builder know what to pass? Commented Nov 16, 2020 at 1:02
  • getItems is the callback function. I want builder to pass whatever arguments I have specified when defining my callback (a, b, or c). With your answer, you've got me doubting that this is even possible, but I would have thought so. XD Commented Nov 16, 2020 at 1:13
  • I've updated my code to show that these parameters will also be passed via return async (...): Promise<Baz> => { . Commented Nov 16, 2020 at 1:22

1 Answer 1

0

If anybody googles this, finally went with :

function builder<T extends Foo>(
  getItems: (...addedParams: any[]) => Promise<T[]>, 
) {
  return async (...addedParams: any[]): Promise<Baz> => { 
    const items = await getItems(...addedParams); 
    // some manipulation here
    return items;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.