如何在TypeScript中判断泛型T是否继承特定类型并返回布尔值
判断泛型参数是否继承特定类型B
现有外部定义的类型A以及继承A的类型B,已定义泛型接口Config<T>,需要实现isTypeB函数,调用时判断泛型参数T是否继承B,是则返回true,仅继承A则返回false。
相关代码(修正语法错误后)
// 外部定义的类型 // type A; // type B extends A; interface Config<T extends A> { endpoint: 'my/path'; // 其他A和B共有的属性 } const isTypeB = <T extends A>(config: Config<T>): boolean => { // 需实现判断逻辑 };
实现方案
TypeScript的泛型类型仅存在于编译阶段,运行时无法直接获取T的类型信息,必须借助运行时可识别的标识来判断,分两种场景处理:
场景1:A和B是类
如果A、B是类而非接口/类型别名,可通过类实例的instanceof关键字判断:
// 外部定义的类 class A {} class B extends A {} interface Config<T extends A> { endpoint: 'my/path'; data: T; // 包含T类型的实例属性 } const isTypeB = <T extends A>(config: Config<T>): boolean => { return config.data instanceof B; };
场景2:A和B是接口/类型别名
接口在运行时不存在,需通过以下两种方式判断:
添加类型标记字段:在
Config中定义一个编译时推导、运行时可读取的标记字段:type A = { /* A的属性 */ }; type B = A & { /* B的独有属性 */ }; interface Config<T extends A> { endpoint: 'my/path'; type: T extends B ? 'B' : 'A'; // 自动推导类型标记 } const isTypeB = <T extends A>(config: Config<T>): boolean => { return config.type === 'B'; };检查独有属性:如果B有A没有的独有属性,可通过检查该属性是否存在判断:
const isTypeB = <T extends A>(config: Config<T>): config is Config<B> => { // 假设B有独有属性`bUniqueProp` return 'bUniqueProp' in (config as unknown); };
内容的提问来源于stack exchange,提问作者Ewan
相关产品推荐
相关产品推荐

