TypeScript 中如何表示当前类的类型

在 TypeScript 中,我们有时需要在类的内部或外部引用"当前类的类型"。这在实现设计模式(如工厂模式、单例模式)、继承或泛型类时非常有用。本文将总结如何在不同上下文中表示当前类的类型。


一、在类的静态方法或属性中引用当前类的类型

使用 typeof 表达当前类的构造函数类型:

ts 复制代码
class MyClass {
  static create(): MyClass {
    return new this(); // this 指的是当前构造函数
  }
}

但如果你要准确标注当前类的类型,可以这样写:

ts 复制代码
class MyClass {
  static factory(cls: typeof MyClass): MyClass {
    return new cls();
  }
}

示例:支持继承的工厂方法

ts 复制代码
class Base {
  static create<T extends typeof Base>(this: T): InstanceType<T> {
    return new this();
  }
}

class Sub extends Base {}

const instance = Sub.create(); // 类型是 Sub

二、在类的内部方法中引用当前实例的类型

1. 使用 this 类型

ts 复制代码
class Builder {
  setName(name: string): this {
    // 可以继续调用其他方法
    return this;
  }
}

2. 示例:链式 API

ts 复制代码
class BaseBuilder {
  setName(name: string): this {
    return this;
  }
}

class AdvancedBuilder extends BaseBuilder {
  setAge(age: number): this {
    return this;
  }
}

const builder = new AdvancedBuilder()
  .setName("Alice")
  .setAge(30); // builder 类型是 AdvancedBuilder

三、获取类本身的类型 vs 实例类型

表达式 含义
typeof MyClass 表示类的构造函数类型
MyClass 表示类实例的类型
InstanceType<typeof MyClass> 从构造函数类型提取实例类型

示例:

ts 复制代码
class Person {
  name = "John";
}

type PersonConstructor = typeof Person; // 构造函数类型
type PersonInstance = InstanceType<typeof Person>; // 实例类型

四、限制参数为"当前类类型"的技巧

ts 复制代码
class Animal {
  cloneFrom(other: this): void {
    Object.assign(this, other);
  }
}

五、结合泛型的"当前类类型"

ts 复制代码
class FluentBase<Self extends FluentBase<Self>> {
  doSomething(): Self {
    return this as Self;
  }
}

class FluentChild extends FluentBase<FluentChild> {
  extra(): FluentChild {
    return this;
  }
}

const result = new FluentChild().doSomething().extra(); // 类型安全!

六、总结

目的 用法
表示当前类的构造函数类型 typeof ClassName
表示当前类的实例类型 ClassNameInstanceType<typeof ClassName>
在类内部方法中表示实例类型 this
在静态方法中引用当前构造函数 this: typeof ClassNamethis: T
用泛型表示当前类 <Self extends Base<Self>>

如果你正在实现链式 API、工厂方法或继承层次较复杂的类库,这些技巧都可以大大增强类型的表达力和安全性。

相关推荐
suaizai_1 分钟前
AI Agent如何懂你:四层能力拆解
java·前端·人工智能
invicinble12 分钟前
把握前端项目的核心(vibecoding)
前端
0end141 分钟前
AI Agent 学习笔记(三):上下文工程(下)—— KV Cache、提示词设计与 Agent Skills
前端·aigc·ai编程
CAD老兵1 小时前
在浏览器里对比 DWG/DXF 图纸 —— @mlightcad/cad-diff-viewer
前端·javascript·github
JasonYin1 小时前
AI 定义的 H5移动端 开发规范,直接抄作业!
前端
诗章与猫1 小时前
Leaflet 渲染 100 万 marker 卡成 PPT?我用 WebGL 重写了渲染器
前端
用户921080262861 小时前
在 AI 代码生成项目里接入 Thought:别展示“玄学思维链”,只展示用户真正关心的工具调用
前端
艾醒(AiXing-w)1 小时前
LangChain 1.0 入门(二):LangChain 全模型标准化接入最佳实践(小白参数详解版)
前端·javascript·langchain
计算机魔术师2 小时前
我看了 Hugging Face 的 Daily Papers,发现这件事
前端
yu俞娥宝3 小时前
Codex官网前端可抄吗?技术拆解、风险边界与合规借鉴方案
前端