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

TypeScript如何获取父类类型?

获取TypeScript子类的父类类型

Great question! The type you've defined (someType) right now just acts as an identity type—it returns whatever you pass into it, which is why superType ends up being SubClass instead of BaseClass.

To get the superclass type of a subclass in TypeScript, we can leverage conditional types and JavaScript's prototype chain (which TypeScript mirrors in its type system). Here are two common scenarios you might need:

1. 获取父类的构造函数类型

If you want the type of the parent class constructor (e.g., typeof BaseClass from SubClass), use this custom type:

class BaseClass { baseProp: string; }
class SubClass extends BaseClass { subProp: string; }

// 自定义类型:提取子类构造函数的父类构造函数类型
type GetSuperClassConstructor<T> = T extends { __proto__: infer U } ? U : never;

// 获取SubClass的父类构造函数类型
type SuperClassConstructor = GetSuperClassConstructor<typeof SubClass>; 
// 类型为 typeof BaseClass

2. 获取父类的实例类型

If you want the instance type of the parent class (e.g., BaseClass from the SubClass instance type), use this variation:

// 自定义类型:提取子类实例的父类实例类型
type GetSuperClassInstance<T> = T extends { __proto__: infer U } ? U : never;

// 获取SubClass实例的父类实例类型
type SuperClassInstance = GetSuperClassInstance<SubClass>; 
// 类型为 BaseClass

为什么你的原类型不生效?

Your original someType<T> = T extends infer U ? U : T is a no-op—it just infers U as T and returns it. It doesn't interact with the prototype chain to extract the parent class type, which is why it didn't give you the result you wanted.

注意事项

  • This approach works for TypeScript's single-inheritance model. If a class doesn't extend any parent, the type will return never.
  • It relies on the __proto__ property, which is a standard part of JavaScript's prototype system and is supported in TypeScript's type checking.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:48:36