TypeScript returning arbitrary type

33 Views Asked by At

I have a function that, when called, returns an object. The type of the object is unknown to the function, but supposedly known to the caller.

I don't want to use any or implicit any, so I have to choose: do I return unknown or a generic <T> type?

If I return unknown (because I don't know/care what the type is), I force the callers to cast the result, which is not convenient - especially in an async context, where they will need to await the result.

async function getSomething(): Promise<unknown> {
  return JSON.parse(await unknownJsonValue());
}

const something = (await getSomething()) as Something;
// use the value - it might not be a Something, but it's clearly the caller's responsibility

If, on the other hand, I use generics, I kind-of promise that the returned object will be what the caller has requested:

async function getSomething<T>(): Promise<T> {
  return JSON.parse(await unknownJsonValue());
}

const something = await getSomething();
// use the value - it might not be a Something even though the library "promised" that it is

If for some reason the result wasn't what the user expected, I broke the contract.

What are the pros and cons of each approach, other than what I already wrote?

0

There are 0 best solutions below