1243 字
6 分钟
05 · 类与面向对象(含装饰器)
2026-09-30

类在 TS 里是”两样东西”#

一个 class 同时提供:

  • 类型(描述实例的形状);
  • 值(运行时的构造函数)。
class User { constructor(public name: string) {} }
const u: User = new User('a'); // User 作类型
const c: typeof User = User; // typeof User 才是"构造函数类型"

搞不清这一点,就会在”想给类本身加约束”时卡住(比如”传一个类进来而不是实例”)。


修饰符:编译期 vs 运行时#

class Account {
public owner: string; // 默认就是 public,一般省略
private balance = 0; // 编译期私有:运行时仍可 obj['balance'] 访问
protected currency = 'CNY'; // 子类可见
readonly id: string; // 只能构造时赋值
#secret = 'x'; // 运行时真私有(ES 私有字段)
constructor(public readonly name: string, id: string) {
this.id = id; // 参数属性简写:自动声明 + 赋值
}
}
修饰符编译期运行时何时用
private外部不可访问仍可访问(obj['x'])团队内部约定,够用
#field外部不可访问真不可访问(语法层面)需要防”有人绕过”(库/SDK)
protected子类可见可访问有继承体系时
readonly不可重新赋值可改(浅层)不可变字段

实践:业务代码用 private 足够;对外发布的类用 #,因为使用者可能用 as any 或下标绕过。


abstract / implements / override#

abstract class Repository<T> {
abstract findById(id: string): Promise<T | null>; // 只声明,不实现
async exists(id: string): Promise<boolean> { // 模板方法:公共逻辑放在基类
return (await this.findById(id)) !== null;
}
}
interface Cacheable { cacheKey(): string; }
class UserRepo extends Repository<User> implements Cacheable {
override async findById(id: string) { return db.users.find(id); }
cacheKey() { return 'user'; }
}

三个要点:

  1. abstract 是”契约 + 部分实现”:适合模板方法模式(基类定流程,子类填细节)。
  2. implements 只检查形状,不继承实现:一个类可以实现多个接口,但只能 extends 一个类。
  3. override 必须写(noImplicitOverride: true 时):防止基类改方法名后,子类悄悄变成一个”没人调用的新方法”。

继承 vs 组合:TS 只给你单继承,这是提醒#

// ❌ 继承链一深,改基类就全员地震
class Base { log() {} }
class ApiClient extends Base {}
class GithubClient extends ApiClient {} // 只为了复用 log
// ✅ 组合:把能力做成独立对象
const logger = { log: (m: string) => console.log(m) };
class GithubClient {
constructor(private deps: { logger: typeof logger }) {}
}

判断标准:“is-a” 用继承,“has-a / can-do” 用组合。前端业务里 90% 的情况是组合。


装饰器:只为”读懂框架”#

TypeScript 有两套装饰器,混用会踩坑:

Legacy(experimentalDecorators)Stage 3(TS 5.0+,默认)
开启方式"experimentalDecorators": true无需配置
参数形态(target, key, descriptor)(value, context)
谁在用Angular、NestJS、TypeORM、老 MobX新库、TC39 标准
能否加新字段能(改 descriptor)只能返回替换值

新项目不要主动用装饰器(它是元编程,调试栈难读)。但读框架源码必须认得:

// Legacy:方法装饰器(NestJS 的 @Get() 就是这个形态)
function Log(target: unknown, key: string, descriptor: PropertyDescriptor) {
const original = descriptor.value;
descriptor.value = function (...args: unknown[]) {
console.log(`→ ${key}`, args);
return original.apply(this, args);
};
return descriptor;
}
class UserService {
@Log
find(id: string) { return { id }; }
}
// Stage 3:同样的需求,形态完全不同
function logged<This, Args extends unknown[], R>(
value: (this: This, ...args: Args) => R,
context: ClassMethodDecoratorContext,
) {
return function (this: This, ...args: Args): R {
console.log(`→ ${String(context.name)}`, args);
return value.apply(this, args);
};
}

判断你项目用的是哪套:看 tsconfig.json 有没有 experimentalDecorators,以及依赖里有没有 reflect-metadata。


常见坑#

现象根因解法
子类重写方法后行为没变基类方法名改了,子类成了新方法开 noImplicitOverride,写 override
private 字段被外部改了private 只是编译期用 # 字段
装饰器报 Unable to resolve signature两套装饰器混用检查 experimentalDecorators 与 TS 版本
this 丢失方法被解构传递用箭头函数属性,或 bind
抽象类被直接 new忘了 abstract加 abstract class
类作为值传递时类型写错用了实例类型而非 typeof Class用 typeof X 或 new () => X

验收清单#

  • 对外暴露的类,敏感字段用 # 而不是 private
  • 开了 noImplicitOverride,子类重写都写 override
  • 能说出 implements 与 extends 的差别(一个查形状、一个继承实现)
  • 继承层级不超过 2 层,超出的部分改成组合
  • 能判断项目用的是哪一套装饰器(看 tsconfig 与依赖)
  • 没有为了”复用一行代码”而建立继承关系

练习#

  1. 验证 private 与 # 的差别:写一个 private x 和一个 #y,用 obj['x'] 和 obj['y'] 分别访问。
    自检:能说明”为什么给外部用的 SDK 要用 #”(编译期约束拦不住 as any)。
  2. 写一个 legacy 方法装饰器:给方法加上”耗时统计”,不改变原方法签名。
    自检:能解释 descriptor.value 被替换后,this 为什么必须用 apply 传递。
  3. 重构一段继承:把”三个子类都继承了一个带 log() 的基类”改成组合注入 logger。
    自检:能说出重构后”新增一个类不需要再改基类”的好处。
05 · 类与面向对象(含装饰器)
https://haolo.cloud/blog/posts/typescript-roadmap-05-class-and-oop/
作者
Ethan
发布于
2026-09-30
许可协议
CC BY-NC-SA 4.0
本系列目录
TypeScript学习路线 · 共 19 篇 · 当前第 6 篇
  1. 0 TypeScript 从类型到类型安全 · 路线总览
  2. 1 环境与工具链
  3. 2 基础类型与字面量
  4. 3 对象类型:interface / type / 索引签名
  5. 4 函数类型
  6. 5 类与面向对象(含装饰器) 当前
  7. 6 泛型基础
  8. 7 工具类型与类型运算
  9. 8 联合、交叉与类型守卫
  10. 9 条件类型与 infer
  11. 10 类型兼容性与变型
  12. 11 运行时校验与类型安全边界
  13. 12 声明文件与类型生态
  14. 13 从 JS 渐进迁移到 TS
  15. 14 tsconfig 与类型检查性能
  16. 15 类型测试与发布类型
  17. 16 与框架/运行时集成
  18. 17 毕业项目:写一个类型安全的 API SDK(契约、校验、类型推导与发布)
  19. 18 TypeScript 5.x 现代特性与工程落地(扩展篇)
查看路线总览