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

如何让函数根据条件返回可选泛型类型?

解决TypeScript泛型函数返回类型的精准匹配问题

你的核心需求是让函数返回类型根据是否传入applyDataCallback或指定泛型动态变化,而非固定的Promise<T | string>。以下是两种可行的解决方案:

方案一:函数重载(最直观易读)

通过定义多个函数签名,明确不同参数组合对应的返回类型:

// 重载签名1:传入回调时,返回泛型T的Promise
async function helper<T>(
  config: { body: string },
  applyDataCallback: (value: string) => T
): Promise<T>;

// 重载签名2:不传入回调时,返回string的Promise
async function helper(
  config: { body: string }
): Promise<string>;

// 实现签名(需兼容所有重载场景)
async function helper<T = string>(
  config: { body: string },
  applyDataCallback?: (value: string) => T
): Promise<T | string> {
  const body = typeof applyDataCallback === 'function'
    ? applyDataCallback(config.body)
    : config.body;

  return body;
}

使用效果:

  • 不传回调:helper({ body: "hello" }) → 返回Promise<string>
  • 传入回调:helper({ body: "123" }, val => parseInt(val)) → 返回Promise<number>
  • 指定泛型并传回调:helper<number>({ body: "456" }, val => parseInt(val)) → 返回Promise<number>

方案二:泛型条件类型(更灵活的类型推导)

利用TypeScript的条件类型,让返回类型根据泛型参数动态判定:

const helper = async <T = never>(
  config: { body: string },
  // 仅当T不是默认的never时,才允许传入回调
  applyDataCallback?: T extends never ? never : (value: string) => T
): Promise<T extends never ? string : T> => {
  const body = typeof applyDataCallback === 'function'
    ? (applyDataCallback as (value: string) => T)(config.body)
    : config.body;

  return body as Promise<T extends never ? string : T>;
}

逻辑说明:

  • 当不指定泛型且不传回调时,T默认是never,返回类型为Promise<string>
  • 当指定泛型或传入回调时,T会被推断为对应类型,返回类型为Promise<T>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 13:27:27