When working with my API, I have noticed a consistent pattern where it returns either a specific type or a TypeScript type called BadResult
, as shown below:
type Result1 = CreatedPersonResult | BadResult;
type Result2 = CreatedRoleResult | BadResult;
To streamline my code, I am looking to create a generic wrapper function that can accept either Result1
or Result2
as input and return only the successful result, such as CreatedPersonResult
.
I believe leveraging the Exclude
option in TypeScript might be the solution.
In cases where the result is a BadResult
, throwing an error would be acceptable.
const resolveActualType = (result: T): Exclude<T, BadResult> => {
// if(... is BadResult) {
// throw Error();
// }
return result;
}