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

如何让TypeScript函数根据type参数自动推导matcher参数类型?

解决方案

你的判断是对的,问题出在泛型T的推断逻辑上——当前foo函数没有显式声明泛型,直接使用带默认值的Options接口时,T会被默认解析为整个EventType枚举,导致matcher的参数类型始终是First | Second的联合类型,无法根据type值缩小范围。

要实现预期的类型自动推断,只需要把foo改成泛型函数,让TypeScript从传入的type参数中自动推导T的具体值即可:

enum EventType {
  First = 'first',
  Second = 'second',
}

type First = {
  first: string;
  type: EventType.First;
};
 
type Second = {
  second: string;
  type: EventType.Second;
};

type Data = First | Second;

interface Options<T extends EventType> {
  matcher: (data: Extract<Data, { type: T }>) => boolean;
  type: T;
}

// 将foo改为泛型函数,约束T继承EventType
function foo<T extends EventType>(options: Options<T>) {
  // ... 函数逻辑
}

// 调用示例,此时matcher的data会自动推导为对应类型
foo({
  matcher: data => {
    // data 类型为First,可以直接访问data.first
    return data.first.length > 0;
  },
  type: EventType.First,
});

foo({
  matcher: data => {
    // data 类型为Second,可以直接访问data.second
    return data.second.includes('test');
  },
  type: EventType.Second,
});

关键改动说明

  • 移除Options接口中T的默认值= EventType,避免默认解析为联合类型
  • 让foo函数本身成为泛型函数,将T的推断来源绑定到传入的options.type参数上
  • TypeScript会根据type的具体枚举值,自动将Extract<Data, { type: T }>解析为对应的First或Second类型,从而让matcher的参数获得严格的类型约束

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 15:50:59