打字稿错误我在我的承诺包装器中不明白
Typescript error I don't understand in my promise wrapper
为什么我不能 return 通过链接 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]))
// ---
}
这是我得到的错误。我把它读作我 return 未在某种程度上考虑“then & catch”链的承诺。并通过 async/await (工作方式)和分离承诺,编译器理解我想要 return 结果 <> 承诺?
如果我想使用 promise 链,我如何告诉打字稿我的 promise 会 return 结果<>?
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]);
为什么我不能 return 通过链接 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]))
// ---
}
这是我得到的错误。我把它读作我 return 未在某种程度上考虑“then & catch”链的承诺。并通过 async/await (工作方式)和分离承诺,编译器理解我想要 return 结果 <> 承诺?
如果我想使用 promise 链,我如何告诉打字稿我的 promise 会 return 结果<>?
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]);