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

如何从TypeScript泛型中提取泛型参数的类型约束

可行实现方案

完全可以实现,以下是兼容绝大多数 TypeScript 版本的实现方式:

核心思路

利用 TypeScript 泛型参数的约束收窄特性,结合条件类型的infer语法提取约束类型:当我们给带约束的泛型参数传入any时,TS 会自动将any收窄到该泛型的约束范围内,我们只需要把这个收窄后的类型推断出来即可。

完整代码实现

// 你原有的泛型定义
interface SomeWrapper<TValue extends string | number | boolean | null = string> {
  // ...
}

// 提取工具类型实现
type DoSomeMagicHere<T> = T extends SomeWrapper<infer U> ? U : never;

// 调用效果
type SomeConstraint = DoSomeMagicHere<SomeWrapper<any>>;
// 此时 SomeConstraint 的类型为:string | number | boolean | null

通用多场景适配

如果需要做通用的单泛型参数约束提取,不需要绑定具体的SomeWrapper类型,可以调整工具类型如下(兼容TS4.7及以上版本):

type GetSingleGenericConstraint<G> = 
  // @ts-ignore 忽略泛型参数数量校验,仅适配单参数泛型场景
  G<any> extends infer Instance 
  ? Instance extends G<infer Constraint> 
    ? Constraint 
    : never 
  : never;

// 调用效果和之前一致
type SomeConstraint = GetSingleGenericConstraint<SomeWrapper>;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 23:15:02