TypeSafe external API ?

I am currently communicating with an external API and after falling in love with TRPC, I would like to make this communication with the external API as TypeSafe as possible as well.

I am however kinda failing in the basics of figuring out how to return different types, depending on the inputs of my function call.

Example, i can call the same endpoint on my external API with the parameter "withItems", which kinda ends up mimicking the Prisma version of "include" - but unlike the great work Prisma has done - I am unsure how to detect if the programmer (in this case - mostly me), has passed this parameter to my API call function and return a different typesafe-type. I therefore always end up returning a mixed result (one type - or the other).

My models are these (simplified):

interface Order{
  id: number,
  name: string,
  date: Date,
}

interface Item{
  name: string,
  value: number,
}

interface Order_Items{
  items: Item[];
}


My first attempts where to make a function call where I did something similar to this:

 function getOrder(data:{
  id:number,
  withItems?: boolean,
}): Order | (Order&Order_Items) {
  /* here i would call the external API with data as the POST data, but return two different types, if withItems was in the data or not */ 
}

const theOrder1 = getOrder({id: 1,})
const theOrder2 = getOrder({id: 1, withItems:true});


However my initial approach resulted in my having to typecast the result from getOrder - since I never succeded in making a "strong" connection between the parameters of the call, and the result.

In comes Zod - which i believe would be my saviour here - but I fail to get Zod working. I simply cannot grasp my head around how I would implement Zod in this kind of structure and get type-safe return.

Hope you can help (and I have formulated my question clear enough)
Was this page helpful?