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

透传函数中能否将字符串类型推断为实际取值而非string?

如何让透传函数推断字符串属性的具体字面量类型?

当然可以实现这个需求,问题出在你当前的函数参数类型是固定的{name: string},TypeScript会自动把传入的字符串字面量(比如"Foo"、"Bar")拓宽为string类型。要保留具体的字面量类型,只需要给透传函数加上泛型约束即可:

function passthrough<T extends { name: string }>(arg: T): T {
  return arg;
}

原理说明

这里的泛型T会捕获传入参数的具体类型信息,包括字符串字面量。函数返回值指定为T,就能让TypeScript推断出返回值的类型和传入参数完全一致。

验证示例

用你提供的代码测试:

const res = passthrough(Math.random() < 0.5 ? {name: "Foo"} : {name: "Bar"});
// 此时res的类型被正确推断为 {name: "Foo"} | {name: "Bar"}

这样就能得到你期望的类型推断结果,而不是统一的{name: string}。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 23:20:53