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

TypeScript中能否指定条件返回值类型,实现返回字段关联类型推断

实现方案

可以使用 TypeScript 的判别联合类型实现你要的互斥类型推断效果,核心是把原函数的可选属性返回类型替换为两种完全互斥的结构联合:

修改后的函数定义

// 定义互斥的返回结果类型
type CaptureResult<T> = 
  | { error: undefined; result: T }
  | { error: Error; result: undefined }

const capture = <T>(
  callback: () => T
): CaptureResult<T> => {
  try {
    return { result: callback(), error: undefined };
  } catch (err) {
    return { result: undefined, error: err as Error };
  }
};

用法示例

你的原有用法无需修改,TS 会自动完成类型收窄,不会再抛出2532错误:

const { result, error } = capture<number>(() => foo());
if (error) {
  badPath();
  // 此分支内 result 被自动推断为 undefined
  return;
}
// 此分支内 error 被自动推断为 undefined,result 被推断为 number 类型
console.log("hooray we got a result", result)

可选增强方案

如果需要兼容更低版本的 TS,或者想要更稳定的类型收窄效果,可以给返回结果加一个明确的判别字段:

type CaptureResult<T> = 
  | { success: true; result: T; error: undefined }
  | { success: false; result: undefined; error: Error }

const capture = <T>(callback: () => T): CaptureResult<T> => {
  try {
    return { success: true, result: callback(), error: undefined };
  } catch (err) {
    return { success: false, result: undefined, error: err as Error };
  }
};

// 用法
const res = capture<number>(() => foo());
if (!res.success) {
  badPath();
  return;
}
console.log(res.result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 15:54:03