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

如何获取<string, function>类型对象中所有函数参数的联合类型?

TypeScript:提取对象中所有函数参数的联合类型

给定如下TypeScript常量对象:

export const templates = {
  [EventType.EventType1 + OutputSources.Email]: (params: { documentName: string; link: string }) => {
    return "some html data";
  },
  [EventType.EventType2 + OutputSources.Email]: (params: { documentName: string }) => {
    return "some html data";
  },
  [EventType.EventType1 + OutputSources.Notification]: (params: { documentName: string }) => {
    return "some html data";
  },
} as const;

需要生成包含该对象中所有函数参数的联合类型,期望结果为:

type possibleFunctionArgs = {documentName:string,link:string} | {documentName:string}

之前尝试以下写法失败:

type lastFailingAttemptToGetTypes = Parameters<typeof templates[keyof typeof templates]>

这是因为函数参数处于逆变位置,当Parameters作用于联合函数类型时,会自动收缩为所有函数参数类型的交集,而非我们需要的联合类型。

正确实现方式

利用分布式条件类型逐个处理每个函数类型,提取其参数并组成联合:

// 提取对象中所有函数的联合类型
type TemplateFunctions = typeof templates[keyof typeof templates];

// 遍历每个函数,提取第一个参数的类型
type possibleFunctionArgs = TemplateFunctions extends (...args: [infer P]) => any ? P : never;

或者简化为单行写法:

type possibleFunctionArgs = typeof templates[keyof typeof templates] extends (...args: [infer P]) => any ? P : never;

执行后就能得到期望的联合类型:{documentName: string; link: string} | {documentName: string}。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 17:02:15