Why can't I just return the promise by chaining then & catch, i don't see the difference here.
type SuccessResponse<T> = [T, null]
type ErrorResponse<U> = [null, U]
type Result<T, U> = Promise<SuccessResponse<T> | ErrorResponse<U>>
export const promiseWrapper = async <T, U extends Error>(
promise: Promise<T>
): Result<T, U> => {
// --- This works ---
try {
const data = await promise
return Promise.resolve([data, null])
} catch (error) {
return Promise.resolve([null, error])
}
// ---
// --- Doing this instead cause TypeScript error ---
// return promise
// .then((data) => [data, null])
// .catch((error) => Promise.resolve([null, error]))
// ---
}
This is the error i got. I read it as the promise i return not considered the "then & catch" chain in some way. And by doing it with by async/await (The working way) and decouple the promise the compiler understand that i want to return the Result<> promise?
If i want to use the promise chain how can I tell typescript that my promise will return Result<>?
Type '(T | null)[] | [null, any]' is not assignable to type 'SuccessResponse<T> | ErrorResponse<U>'.
Type '(T | null)[]' is not assignable to type 'SuccessResponse<T> | ErrorResponse<U>'.
Type '(T | null)[]' is not assignable to type 'ErrorResponse<U>'.
Target requires 2 element(s) but source may have fewer.
Either
which does make more sense but I'm not sure a tuple in a promise is the best way to implement it.