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

如何让TypeScript函数返回独特联合类型而非归一化联合类型?

解决TypeScript联合类型自动添加可选undefined字段的问题

需要让函数根据返回值自动推导结果类型,且无法为所有场景添加显式返回类型注解。举例说明:

  • f1函数返回{ kind: 'a' } | { kind: 'b' },类型推导符合预期;
  • f2函数因其中一个返回值多了字段x,TypeScript会将返回类型归一化为归一化联合类型(normalized union):{ kind: 'a', x?: undefined } | { kind: 'b', x: number },但实际期望的返回类型是{ kind: 'a' } | { kind: 'b', x: number }。

即使使用as const也无法避免出现x?: undefined的情况,最终通过恒等函数可以解决该问题:

function fix<const T>(v: T): T { return v; } // 恒等函数
function f2() {
    return Math.random() > 0.5 ? fix({ kind: 'a' }) : fix({ kind: 'b', x: Math.random() });
}
f2(); // 返回类型:{ kind: "a"; } | { kind: "b"; x: number; }

注:测试使用的TypeScript版本为5.7.0-dev.20240928(typescript@next)

内容的提问来源于stack exchange,提问作者Trident D'Gao

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 21:12:35