Home > Mobile >  Mapping any object of [k: string]: any to a Generic type
Mapping any object of [k: string]: any to a Generic type

Time:10-27

I have a function that return an Output generic type. This function makes an API call that returns a json object. I want my function to return this json mapped to its Output Generic type

Here is an example:

function myFunc<Output>(): Promise<Output> {
  const apiRes: {[Key: string]: string} = getFromAPI()

  return apiRes as Output
}

When I try this, typescript complain about the types not being similar enough, which is not surprising. I guess the best approach would be to create a function that maps every property of apiRes to those of Output but I have no idea how to get the attributes and values types of a Generic Type

CodePudding user response:

If you want to "take responsibility" for the type returned by getFromAPI(), simply so something like this:

return getFromAPI()
   .then(res => res as unknown as Output);

I'm not sure if it's what you expect?

  • Related