I have the following function that allows me to handle async errors similar to Go.
type AsyncResults<ErrorType, DataType> = Promise<
readonly [undefined, DataType] | readonly [ErrorType, undefined]
>;
const asyncHandler = <ErrorType, DataType>(
asyncFunc: Promise<DataType>,
): AsyncResults<ErrorType, DataType> => {
return asyncFunc
.then((data: DataType) => [undefined, data] as const)
.catch((error: ErrorType) =>
Promise.resolve([error, undefined] as const),
);
};
When I call it, I usually get error type to be 'unknown', which is ok, but my result type is always whatever is inferred union undefined
const [err, verifiedUser] = await asyncHandler(
getPasswordVerifiedUser(db, {
email,
password,
}),
);
if (err) throw err
const user: VerifiedUser = {
firstName: verifiedUser.firstName (TS complains that object may be undefined)
}
So verifiedUser above has inferred type 'Document | undefined'. Is there a way for TypeScript to know that if err is undefined then verifiedUser cannot be undefined (and vice versa)? I want that if I handle the err by throwing or returning, TS recognizes that verifiedUser can no longer be undefined.