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

如何在自定义泛型类型中替换泛型参数?

如何在自定义泛型类型中替换泛型参数?

给定以下TypeScript代码:

class X<T> {
    _t: T|null = null
}

class Y<T> {
    _y: T|null = null
}

type ReplaceT<V extends unknown<any>, NewT> = unknown // 需要实现这里

const x = new X<string>
const y = new Y<string>

// 假设传入的类型只有一个泛型参数
type T1 = ReplaceT<typeof x, number> // 期望得到 X<number>
type T2 = ReplaceT<typeof x, boolean> // 期望得到 X<boolean>
type T3 = ReplaceT<typeof y, boolean> // 期望得到 Y<boolean>

需求是实现ReplaceT类型工具,将传入的泛型实例类型的泛型参数替换为指定的新类型。


这个需求可以实现,利用TypeScript的条件类型与泛型推断能力即可完成:

type ReplaceT<Instance, NewT> = Instance extends infer GenericType<infer _> 
  ? GenericType<NewT> 
  : never;

原理说明

  • 通过条件类型Instance extends infer GenericType<infer _>匹配泛型实例的结构,提取出原始的泛型类型GenericType,同时忽略原有的泛型参数_
  • 用指定的NewT作为新参数,构造出目标泛型类型GenericType<NewT>

替换后,T1、T2、T3会被正确推断为期望的类型。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 04:30:09