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

如何引用对象类型中重载匿名函数的特定函数类型?

提取重载函数类型中的单个签名

你定义的type a是包含多个重载签名的函数类型,要单独引用其中某一个签名,可以通过条件类型结合类型推断或者构造重载元组的方式实现:

方法1:直接推断指定重载

如果目标重载的参数结构明确,可直接用条件类型提取:

type a = {
    (name : string) : string;
    (name : string, id : number) : string;
}

// 获取第一个重载(单参数版本)
type b = a extends (name: infer Name) => infer Return ? (name: Name) => Return : never;
// 此时 b 等价于 (name: string) => string

方法2:构造重载元组统一管理

如果需要灵活获取任意位置的重载,可先将所有重载转换为元组类型,再通过索引访问:

type a = {
    (name : string) : string;
    (name : string, id : number) : string;
}

// 将重载函数类型转换为签名元组
type OverloadTuple<T> = 
    T extends { 
        (...args: infer A1): infer R1;
        (...args: infer A2): infer R2;
    } ? [(...args: A1) => R1, (...args: A2) => R2] : never;

// 通过索引获取第一个重载
type b = OverloadTuple<a>[0]; // 等价于 (name: string) => string
// 获取第二个重载
type c = OverloadTuple<a>[1]; // 等价于 (name: string, id: number) => string

说明

  • 方法1适合只需要提取单个固定重载的场景,写法简洁;
  • 方法2适合需要多次访问不同重载的场景,元组索引对应重载的定义顺序。

内容的提问来源于stack exchange,提问作者A. L

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 23:18:15