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

