0

Sorry this could well be a duplicate as I see lots of similar questions just haven't yet managed to apply those examples to my situation...

Given I call my function loadStuff() like so:

loadStuff({
  dataExample1: loadDataExample1Fn(),
  dataExample2: loadDataExample2Fn(),
});

Where:

  • There could be 1 to many dynamic keys to data load calls
  • The example loadDataExample1Fn has signature () => LoadedData<DataExample1>
  • The example loadDataExample2Fn has signature () => LoadedData<DataExample2>

I want the return type to be:

LoadedData<{ dataExample1: DataExample1, dataExample2: DataExample2 }>

Edit: Added Typescript playground example

Anyone able to point me in the right direction in getting typescript support on the returned result?

2
  • 2
    Can you create a typescript playground that includes all the related types? Commented Mar 5, 2022 at 14:53
  • Sure, added above. Commented Mar 5, 2022 at 15:09

1 Answer 1

1

You can indeed! To do this you'll need to make your function generic, and then generate a return type from the inferred generic type using conditional types

const loadStuff = <L extends { [x: string]: LoadedData<any> }>(
  loadedDataItems: L
): LoadedData<{
  [k in keyof L]: L[k] extends LoadedData<infer D> ? D : never;
}> => {
  // Stuff
};
Sign up to request clarification or add additional context in comments.

1 Comment

Great - thanks very much. I don't pretend to completely follow this but will do some reading. 👍

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.