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

如何获取TypeScript中Subject实例的泛型类型?

获取Subject实例的泛型类型

在TypeScript中,你可以通过条件类型结合类型推断提取Subject实例的泛型参数,无需重复定义类型或接口,具体实现如下:

方法1:定义工具类型复用

先声明一个通用工具类型,专门提取Subject的泛型参数:

import { Subject } from 'rxjs';

// 工具类型:提取Subject的泛型参数类型
type ExtractSubjectGeneric<T extends Subject<any>> = T extends Subject<infer U> ? U : never;

// 你的原代码
const sub = new Subject<{ id: string; value: string; }>();

// 使用工具类型标注item
const item: ExtractSubjectGeneric<typeof sub> = { id: '1', value: 'value' };

方法2:内联条件类型(无需额外工具类型)

如果只是单次使用,也可以直接写内联的条件类型,省去工具类型的定义:

import { Subject } from 'rxjs';

const sub = new Subject<{ id: string; value: string; }>();

const item: typeof sub extends Subject<infer U> ? U : never = { id: '1', value: 'value' };

原理说明

核心用到TypeScript的infer关键字,它允许在条件类型中推断泛型参数的具体类型:

  • T extends Subject<infer U>:检查类型T是否为Subject的实例,若是则将Subject的泛型参数推断为U
  • 最终返回U,也就是我们需要的泛型类型

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 15:05:14