1243 字
6 分钟
05 · 类与面向对象(含装饰器)
类在 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'; }}三个要点:
abstract是”契约 + 部分实现”:适合模板方法模式(基类定流程,子类填细节)。implements只检查形状,不继承实现:一个类可以实现多个接口,但只能extends一个类。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 与依赖)
- 没有为了”复用一行代码”而建立继承关系
练习
- 验证
private与#的差别:写一个private x和一个#y,用obj['x']和obj['y']分别访问。
自检:能说明”为什么给外部用的 SDK 要用#”(编译期约束拦不住as any)。 - 写一个 legacy 方法装饰器:给方法加上”耗时统计”,不改变原方法签名。
自检:能解释descriptor.value被替换后,this为什么必须用apply传递。 - 重构一段继承:把”三个子类都继承了一个带
log()的基类”改成组合注入 logger。
自检:能说出重构后”新增一个类不需要再改基类”的好处。
05 · 类与面向对象(含装饰器)
https://haolo.cloud/blog/posts/typescript-roadmap-05-class-and-oop/
本系列目录
本系列目录
- 0 TypeScript 从类型到类型安全 · 路线总览
- 1 环境与工具链
- 2 基础类型与字面量
- 3 对象类型:interface / type / 索引签名
- 4 函数类型
- 5 类与面向对象(含装饰器) 当前
- 6 泛型基础
- 7 工具类型与类型运算
- 8 联合、交叉与类型守卫
- 9 条件类型与 infer
- 10 类型兼容性与变型
- 11 运行时校验与类型安全边界
- 12 声明文件与类型生态
- 13 从 JS 渐进迁移到 TS
- 14 tsconfig 与类型检查性能
- 15 类型测试与发布类型
- 16 与框架/运行时集成
- 17 毕业项目:写一个类型安全的 API SDK(契约、校验、类型推导与发布)
- 18 TypeScript 5.x 现代特性与工程落地(扩展篇)