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

如何在TypeScript类型定义中为映射生成的函数设置动态参数名

问题解答

该需求可以实现,你可以通过构造函数类型参数推断的技巧,动态生成和原类属性名完全一致的函数参数名,完整实现代码如下:

class Person {
  constructor(
    public name: string,
    public age: number,
  ) { }
}

// 辅助类型:生成指定参数名、参数类型的函数类型
type ParamFn<ArgName extends string, ArgType> = 
  (new (arg: Record<ArgName, ArgType>[ArgName]) => void) extends new (p: infer P) => void 
  ? (p: P) => ArgType 
  : never;

type BuilderAccesor<T> = {
  [K in keyof T & string as `with${Capitalize<K>}`]: ParamFn<K, T[K]>
};

type PersonBuilder = BuilderAccesor<Person>;

生成的PersonBuilder类型完全符合你的预期:

type PersonBuilder = {
    withName: (name: string) => string;
    withAge: (age: number) => number;
}

该实现兼容TypeScript 4.1及以上版本,不需要额外配置。

内容的提问来源于stack exchange,提问作者Daniel Rodríguez Meza

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 06:45:03