Home > Software engineering >  Typescript dynamically creating types from object literal
Typescript dynamically creating types from object literal

Time:03-06

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?

CodePudding user response:

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
};
  • Related