#infer actual return type of a function

2 messages · Page 1 of 1 (latest)

dreamy tide
#

Hello everyone, im struggling a bit:

I have an object which keys are either Apple or Banana and its values are a function that takes its "base values" and calculates/adds more attributes to the output object.

The problem is: if I run fruitResolverFunctions.Apple({ sugar: 24, protein: 0 }).kcal the kcal is marked red 🔴 , although its returned Apple: (d) => ... arrow function.

**In the end, I want with the type InferResolvePageDictReturnType to get the "real" return type. **

Probably the ReturnType in FruitDictResolver has to be changed. I just want to make sure that you return at least every value that is inside T.

Here is the code:

interface FruitNutrition {
  sugar: number,
}

interface AppleType extends FruitNutrition {
  protein: number
}
interface BananaType extends FruitNutrition {}

type Fruits = {
  Apple: AppleType,
  Banana: BananaType,
}

type FruitDictResolver = {
  [key in keyof Fruits]: <
    T extends Fruits[key]
  >(
    data: T
  ) => T;
};

const fruitResolverFunctions: FruitDictResolver = {
  Apple: (d) => {
    // do some stuff with the data
    // e.g. calc kcal, etc.
    return { ...d, kcal: 24 };
  },
  Banana: (d) => d,
}

export type InferResolvePageDictReturnType<Key extends keyof Fruits> = Awaited<
  ReturnType<typeof fruitResolverFunctions[Key]>
>;

fruitResolverFunctions.Apple({ sugar: 24, protein: 0 }).kcal

Thank you, anyone that can help would make my day, week, month, world etc. 😄

prime drumBOT
#

@dreamy tide Here's a shortened URL of your playground link! You can remove the full link from your message.

Westsaid#8408

Preview:```ts
interface FruitNutrition {
sugar: number
}

interface AppleType extends FruitNutrition {
protein: number
}
interface BananaType extends FruitNutrition {}

type Fruits = {
Apple: AppleType
Banana: BananaType
}

type FruitDictResolver = {
[key in keyof
...```