我正在制作这个愚蠢的函数,它将对任何函数进行 try/catch 并将其作为包含数据和错误的元组返回
export type CatchReturn<T> = [data: T | undefined, error: unknown | undefined];
export const tcatch = <T>(
tryFunc: (() => T) | (() => Promise<T>)
) => {
try {
const res = tryFunc();
if (res instanceof Promise) {
return res
.then<CatchReturn<T>>((r) => [r, undefined])
.catch<CatchReturn<T>>((e) => [undefined, e]);
} else {
return [res, undefined] as CatchReturn<T>;
}
} catch (e) {
return [undefined, e] as CatchReturn<T>;
}
};
该函数按预期工作,但我无法正确键入返回类型。
目前,返回类型为CatchReturn<T> | Promise<CatchReturn<T>>
但我希望返回类型仅为 CatchReturn<T>
如果tryFunc: (() => T)
和Promise<CatchReturn<T>>
仅当 tryFunc: (() => Promise<T>)
.
例如:
目前的运作情况
const syncRes = tcatch(() => {}) // return type is CatchReturn<T> | Promise<CatchReturn<T>>
const asyncRes = tcatch(async () => {}) // return type is CatchReturn<T> | Promise<CatchReturn<T>>
我期望它如何工作
const syncRes = tcatch(() => {}) // return type should be CatchReturn<T>
const asyncRes = tcatch(async () => {}) // return type should be Promise<CatchReturn<T>>
我尝试在返回类型中使用条件类型,但总是出错,而且我不能 100% 确定这是否可能。
最佳答案
这是函数重载的工作。您只需为 Promise 声明一个函数签名,为其他函数声明另一个函数签名。然后您的实现返回两者的并集:
// signatures
export function tcatch<T>(tryFunc: () => Promise<T>): Promise<CatchReturn<T>>
export function tcatch<T>(tryFunc: () => T): CatchReturn<T>
// implementation
export function tcatch<T>(
tryFunc: (() => T) | (() => Promise<T>)
): CatchReturn<T> | Promise<CatchReturn<T>> {
//...
}
这似乎符合您的预期:
const syncRes = tcatch(() => {}) // CatchReturn<void>
const asyncRes = tcatch(async () => {}) // Promise<CatchReturn<void>>
关于typescript - 仅当接收函数也返回 promise 时,如何将返回类型键入为 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71886977/