typescript - 仅当接收函数也返回 promise 时,如何将返回类型键入为 promise ?

标签 typescript async-await typescript-generics

我正在制作这个愚蠢的函数,它将对任何函数进行 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>>

Playground

关于typescript - 仅当接收函数也返回 promise 时,如何将返回类型键入为 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71886977/

相关文章:

文本框外的iOS 11语义UI文本框模式光标

javascript - 检查所需模块的类型以及它是否根据其类型返回正确的对象

javascript - Angular 2 和 typescript : Cannot access class instance from event handler

javascript - Electron-主进程不等待showOpendialog返回文件内容

c# - 使用 Autofac 的异步 ASP.NET Web API 方法中的 ObjectDisposeException

f# - 等待 System.Threading.Task 并忽略结果?

typescript - Typescript 中的多种类型谓词

Typescript 合并元组

javascript - TypeScript 类型推断 - 函数的通用对象

javascript - Typescript TypeError : . .....toDateString 不是一个函数