Ed .
Ed .

Reputation: 6403

Typescript dynamically creating types from object literal

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:

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?

Upvotes: 0

Views: 66

Answers (1)

Ben Wainwright
Ben Wainwright

Reputation: 4621

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

Upvotes: 1

Related Questions