为什么我不能通过链接then&catch,我看不出这里有什么区别。
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]))
// ---
}
这就是我犯的错误。我把它看作是我所作的承诺,而不被视为";那么&捕获";链在某种程度上。通过async/await(工作方式(和解耦promise,编译器理解我想要返回Result<gt;许诺
如果我想使用promise链,我如何告诉typescript我的promise将返回Result<gt;?
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.
问题是Typescript无法区分[T, null]
和(T|null)[]
。值[data, null]
对于这两种情况都是正确的。
为了解决这个问题,似乎需要指定.then
:返回的类型
return promise
.then<SuccessResponse<T>>((data) => [data, null])
.catch((error) => [null, error]);