I'm trying to find a type for generic error handling that does something like this:
function request(): GenericError<{body:string}> {
if (/* Some condition */) {
return { error: "An error occurred" };
}
return { body: "Things went well" };
}
The goal is to infer that body
exists if error
doesn't, i.e:
const response = request();
if (response.error) return;
/* TypeScript should infer that body can't be undefined here */
I don't know if this is possible in TypeScript and this question might be a duplicate, but I don't know how to word the problem exactly. I tried annotating the function with the answers in this question but none of them could guarantee body
to exist if error
didn't, as far as I could see.