Skip to content
Lv1TypeScript进度 9 / 14

第 9 章:类、修饰符与面向对象 ​

TypeScript 的 class 首先是 JavaScript 的类,然后才是"带类型的类"。它看起来像 Java,但有两处关键差异:private 不是真私有,类型也不参与运行时。


学习目标 ​

  • 会写带字段、构造函数、方法的类,理解字段初始化规则
  • 分清 private、protected、readonly 与 JS 的 # 私有字段
  • 会用参数属性简化构造函数赋值
  • 掌握 implements 与 abstract class 的分工
  • 知道 TS 的类和 Java 的类在哪三点上不同

9.1 最小的类 ​

typescript
class Order {
  id: string
  amount: number

  constructor(id: string, amount: number) {
    this.id = id
    this.amount = amount
  }

  total(taxRate: number): number {
    return this.amount * (1 + taxRate)
  }
}

const order = new Order('A1', 100)
order.total(0.13)   // 113

两个细节:

  1. 字段必须先声明。TS 要求把 id、amount 写在类体里,不能只在构造函数里 this.id = ... 就算数(这叫"声明类字段")。
  2. strictPropertyInitialization 会检查"字段是否在构造函数里被赋值"。如果某个字段确实要晚点赋值(比如异步初始化),用 ! 明确表示"我知道它一开始不存在":
typescript
class Repo {
  private db!: Database   // 稍后由 init() 赋值
  async init() {
    this.db = await connect()
  }
}

但 ! 是"骗编译器",用多了会掩盖真实的初始化顺序 bug。能用默认值或构造函数参数解决的,优先用那两种。


9.2 访问修饰符 ​

typescript
class Account {
  public owner: string          // 默认就是 public,可省略
  private balance: number
  protected bankCode: string

  constructor(owner: string, balance: number, bankCode: string) {
    this.owner = owner
    this.balance = balance
    this.bankCode = bankCode
  }

  deposit(amount: number) {
    this.balance += amount      // 类内部可访问 private
  }
}

class SubAccount extends Account {
  showBank() {
    return this.bankCode        // protected:子类可访问
    // return this.balance      // private:子类也不可访问
  }
}

const acc = new Account('陌阡', 100, 'BOC')
acc.balance   // 报错:private
acc.bankCode  // 报错:protected

private 不是真私有 ​

这是最容易误解的一点:

typescript
const acc = new Account('陌阡', 100, 'BOC')
console.log((acc as any).balance)   // 100,运行时能读到

TS 的 private / protected 只在编译期检查,编译后属性名原样保留,运行时谁都能访问。它防的是"手滑",不是"恶意访问"。

真正运行时私有要用 JS 的 # 字段:

typescript
class Wallet {
  #balance = 0

  add(n: number) {
    this.#balance += n
  }

  get balance() {
    return this.#balance
  }
}

const w = new Wallet()
w.add(10)
console.log(w.balance)   // 10
// w.#balance           // 语法上就不允许,运行时也拿不到
修饰符编译期检查运行时私有适合
private✅❌绝大多数场景,简单直观
protected✅❌有继承体系时
#field✅✅需要真正封装(金额、密钥、内部状态)

# 字段和 private 不能同时用,而且 # 字段对子类也完全不可见。

readonly ​

typescript
class Config {
  readonly env: string

  constructor(env: string) {
    this.env = env        // 只能在声明处或构造函数里赋值
  }

  change() {
    // this.env = 'prod'   // 报错
  }
}

readonly 也是编译期约束,但它拦的是"赋值",对对象内部的可变性无效(和第 5 章一样,是浅层的)。


9.3 参数属性:构造函数里的语法糖 ​

构造函数参数加上修饰符,会自动生成"声明 + 赋值"两件事:

typescript
class User {
  constructor(
    public readonly id: string,
    private name: string,
    protected age = 18
  ) {}
}

等价于:

typescript
class User2 {
  public readonly id: string
  private name: string
  protected age: number

  constructor(id: string, name: string, age = 18) {
    this.id = id
    this.name = name
    this.age = age
  }
}

参数属性非常省代码,也是 NestJS、Angular 依赖注入的标准写法。注意一点:它会生成运行时代码(那些赋值语句),所以它和"可擦除语法"的要求冲突——如果你的项目走 Node 的类型剥离,这类写法要改成显式声明。


9.4 getter 与 setter ​

typescript
class Temperature {
  private _celsius = 0

  get celsius(): number {
    return this._celsius
  }

  set celsius(value: number) {
    if (value < -273.15) throw new RangeError('低于绝对零度')
    this._celsius = value
  }

  get fahrenheit(): number {
    return this._celsius * 9 / 5 + 32
  }
}

const t = new Temperature()
t.celsius = 25
t.fahrenheit   // 77

要点:

  • getter 可以只读(不写 setter 就是只读属性);
  • getter / setter 的类型必须一致;
  • 访问器属性在类型上看起来就是普通属性,调用方无感;
  • 不要在 getter 里做重计算或副作用,调用方不会预期到。

9.5 implements 与抽象类 ​

implements:只做检查,不生成代码 ​

typescript
interface PaymentGateway {
  pay(amount: number): Promise<boolean>
  refund(id: string): Promise<void>
}

class StripeGateway implements PaymentGateway {
  async pay(amount: number) {
    return true
  }
  async refund(id: string) {
    // ...
  }
}

implements 只校验"这个类的实例形状是否满足接口",不会往原型上添加任何东西,也不会改变运行时行为。它和 extends 的区别是:extends 继承实现,implements 只继承约束。

一个类可以 implements 多个接口:

typescript
class Hybrid implements PaymentGateway, Logger { ... }

抽象类:有实现,也有必须由子类补的洞 ​

typescript
abstract class Notifier {
  abstract send(message: string): Promise<void>   // 子类必须实现

  async notifyAll(messages: string[]) {
    for (const m of messages) {
      await this.send(m)          // 可以调用抽象方法
    }
  }
}

class EmailNotifier extends Notifier {
  async send(message: string) {
    // 具体实现
  }
}

// new Notifier()   // 报错:抽象类不能实例化

选择规则:

需求选择
只要"形状约束",不需要共享实现interface + implements
需要共享部分实现,同时留一些方法给子类abstract class
只是组合数据,没有行为用对象类型,别写类

在 AI 应用项目里,Notifier 这种抽象类很适合做"多渠道通知";但更常见的做法是"接口 + 工厂函数",因为不需要继承体系,组合更灵活。


9.6 继承与 override ​

typescript
class Base {
  greet(): string {
    return 'hello'
  }
}

class Derived extends Base {
  override greet(): string {     // override 明确表示"我覆盖了父类方法"
    return `${super.greet()}, world`
  }
}

override 关键字(配合 noImplicitOverride: true)能拦住一类 bug:父类方法改名了,子类里那个同名方法变成"新方法",编译器不报错,你以为还在覆盖。加上 override,这种情况会立刻报错。

super() 必须在访问 this 之前调用:

typescript
class Child extends Base {
  constructor(private x: number) {
    super()          // 必须第一句
    // this.x = x    // 参数属性已自动完成
  }
}

9.7 和 Java 的三点关键差异 ​

维度TypeScriptJava
private编译期检查,运行时可访问运行时也私有(反射除外)
类型编译后擦除,不存在于运行时保留在字节码,可反射读取
接口只做结构检查,不生成代码生成接口类型,运行时存在
重载只在类型层,运行时只有一个实现运行时真正的多方法
字段初始化strictPropertyInitialization 强制检查有默认值,不强制
抽象类abstract,不能 new相同

一句话总结:TS 的类和 Java 的类在写法上高度相似,但在"运行时到底有什么"这件事上完全不同。 你从 Java 带过来的习惯(依赖 private 做安全边界、依赖反射读类型)在 TS 里都不成立。


9.8 常见误区 ​

误区一:private 能防止外部访问。 → 只在编译期。要真私有用 #。

误区二:所有东西都用 class 包起来。 → 大多数业务数据用 interface + 普通函数就够了。类是"带状态和行为的对象",不是万能容器。

误区三:抽象类比接口好,因为有实现。 → 抽象类会引入继承链,耦合更重。能用接口 + 组合解决就别用继承。

误区四:implements 会继承父类的实现。 → 不会。它只检查形状,实现要自己写。

误区五:getter 里可以做任意计算。 → 调用方把它当属性读,重计算会让性能问题变得隐蔽。重逻辑写成显式方法。


本章小结 ​

要点说明
字段声明必须写在类体里;strictPropertyInitialization 要求构造函数赋值
访问修饰符public 默认、private/protected 仅编译期检查
真私有JS 的 #field 运行时也拿不到,敏感状态用它
readonly只能声明处或构造函数赋值,浅层
参数属性构造函数参数加修饰符,自动声明 + 赋值
访问器getter/setter 类型必须一致;别塞重逻辑
implements只校验形状,不生成代码,可多个
抽象类共享实现 + 留抽象方法;不能 new
override显式标记覆盖,防父类改名导致的静默 bug

下一章预告 ​

单个文件写完了,接下来是"文件之间怎么连"。下一章讲 import / export、ESM 与 CommonJS 的真实差异,以及 tsconfig 里那套让人头大的 module、moduleResolution、路径别名配置。

👉 第 10 章:模块与 tsconfig 工程化

本文阅读--次|全站访问--次|访客--人