You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中如何允许用户自定义同步或异步可选方法?

TypeScript 允许同步/异步可选方法的实现方案

你当前重复定义同步和异步版本的可选方法是没必要的,TypeScript 支持通过联合返回类型来同时兼容同步和异步实现,无需重复声明方法。

修正后的类型定义

将每个方法的返回类型改为 HookReturnType | Promise<HookReturnType>,这样实现者既可以返回同步值,也可以返回异步 Promise:

onPinnedError?(info: HavenInfo, req: Request, res: Response): HookReturnType | Promise<HookReturnType>;
onPinnedUnhandledRejection?(info: HavenInfo, req: Request, res: Response): HookReturnType | Promise<HookReturnType>;
onPinnedUncaughtException?(info: HavenInfo, req: Request, res: Response): HookReturnType | Promise<HookReturnType>;

原理说明

  • 同步函数直接返回 HookReturnType,完全匹配联合类型的第一个分支;
  • 异步函数(带 async 关键字)的返回值会自动被包装为 Promise<HookReturnType>,匹配联合类型的第二个分支。

示例实现

两种实现方式都会被编译器正常识别:

  1. 同步实现:
const handler = {
  onPinnedError(info, req, res) {
    console.log("处理同步错误");
    return { success: true } as HookReturnType;
  }
};
  1. 异步实现:
const handler = {
  async onPinnedError(info, req, res) {
    await someAsyncOperation();
    console.log("处理异步错误");
    return { success: true } as HookReturnType;
  }
};

内容的提问来源于stack exchange,提问作者Alexander Mills

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 14:24:55