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

如何用Utility Type提取TypeScript函数的泛型约束?

提取TypeScript泛型函数的约束类型

假设我们有这样一个TypeScript函数:

function foo<T extends Bar>(...) {
  ...
}

怎么从中提取出Bar这个约束类型?我自己尝试写了一段伪代码,但对类型推断不太熟悉:

type ExtractGenericConstraint<T> = T extends ((infer U) => any)? U : never; // 伪代码

期望实现的效果是:

type Constraint = ExtractGenericConstraint<typeof foo> // Constraint == Bar

要实现这个需求,我们可以利用TypeScript的条件类型推断和泛型函数的类型结构来提取约束。具体实现如下:

type ExtractGenericConstraint<T> = 
  T extends <U extends infer C>(...args: any[]) => any 
    ? C 
    : never;

原理说明:

  • 用条件类型匹配泛型函数的结构:T extends <U extends infer C>(...args: any[]) => any,其中infer C会自动捕获泛型参数U的约束类型(也就是示例里的Bar)
  • 如果传入的T是符合该结构的泛型函数,就返回捕获到的C;如果不是,就返回never

验证示例:

// 先定义Bar类型
type Bar = { id: number };

// 目标泛型函数
function foo<T extends Bar>(arg: T) {
  return arg;
}

// 提取约束类型
type Constraint = ExtractGenericConstraint<typeof foo>;
// 此时Constraint的类型等价于Bar,即{ id: number }

如果你的函数包含多个泛型参数,这个类型工具只会提取第一个泛型参数的约束。如果需要处理多泛型场景,可以修改条件类型来对应捕获目标泛型的约束。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 08:48:22