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

TypeScript:无需新变量扩展函数隐式参数类型的方法

无需新变量扩展函数隐式参数类型的实现方法

首先,你尝试的(person: person & { name: string }) => ...写法不可行——这里的第一个person是参数名,而后面的person会被TypeScript当作未定义的类型标识符,直接抛出编译错误。

下面是两种可行的实现方案:

方案1:参数内直接类型断言

不需要创建新变量,直接在赋值和返回时对参数做类型断言即可:

;[{ firstName: "John", lastName: "Smith" }]
.map(person => {
  // 对person断言为原类型+扩展类型,直接赋值name属性
  (person as typeof person & { name: string }).name = `${person.firstName} ${person.lastName}`;
  // 返回时同样断言类型
  return person as typeof person & { name: string };
})

方案2:利用泛型约束实现更优雅的类型推导

通过泛型让TypeScript自动识别原参数类型,并扩展新属性,写法更简洁且类型更安全:

;[{ firstName: "John", lastName: "Smith" }]
.map(<T extends { firstName: string; lastName: string }>(person: T) => {
  // 断言为原泛型类型T扩展name属性
  (person as T & { name: string }).name = `${person.firstName} ${person.lastName}`;
  return person as T & { name: string };
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 05:35:12