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

如何在抽象类中使用TypeScript的InstanceType泛型?

Using InstanceType with Abstract Classes in TypeScript

First, let's recap what InstanceType brings to the table: introduced in TypeScript 2.8, this core utility type lets you extract the return type of a constructor function. Here's its built-in definition from TypeScript's standard library:

/**
 * 获取构造函数类型的返回类型
 */
type InstanceType<T extends new (...args: any[]) => any> = T extends new (...args: any[]) => infer R ? R : any;

It's a super useful tool for type manipulation tasks, but there's a critical limitation—it fails to work with abstract classes. The root cause lies in TypeScript's type system: abstract classes don't have a new signature (since you can't instantiate them directly), so they don't satisfy the T extends new (...args: any[]) => any constraint.

I initially tried to work around this restriction by adjusting the type constraint to accommodate abstract constructors. Here's a modified version that supports abstract classes:

type AbstractInstanceType<T extends abstract new (...args: any[]) => any> = 
  T extends abstract new (...args: any[]) => infer R ? R : any;

The key change here is adding the abstract modifier to the constructor type constraint. This tells TypeScript we want to match abstract class constructor types, not just concrete ones that can be called with new.

You can use it just like the standard InstanceType:

abstract class BaseComponent {
  abstract render(): void;
}

// Correctly resolves to the instance type of BaseComponent
type BaseComponentInstance = AbstractInstanceType<typeof BaseComponent>;

This workaround makes it easy to work with abstract class instance types in scenarios like class hierarchies or dependency injection, where you might need to reference the type of an abstract class's instances without instantiating the class itself.


内容的提问来源于stack exchange,提问作者Alexander O'Mara

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:33:31