TypeScript 类

TypeScript 中的类(Class)详解

TypeScript 的类(class)基于 ES6 类语法,并添加了强大的静态类型支持访问修饰符抽象类装饰器等特性,使其更接近传统面向对象语言(如 Java/C#),同时完全兼容 JavaScript。

1. 基本类声明与实例化

class Person {
  name: string;     // 实例属性(需手动声明)
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  greet(): void {
    console.log(`Hello, I'm ${this.name}`);
  }
}

let alice = new Person("Alice", 30);
alice.greet();  // "Hello, I'm Alice"

参数属性简写(推荐,减少冗余):

class Person {
  constructor(
    public name: string,     // 自动声明 public name 并赋值
    private age: number      // 自动声明 private age 并赋值
  ) {}

  greet(): void {
    console.log(`Hello, I'm ${this.name}`);
    // console.log(this.age);  // OK,在类内部可访问
  }
}

let bob = new Person("Bob", 25);
console.log(bob.name);  // OK
// console.log(bob.age); // 错误:private

2. 访问修饰符(Access Modifiers)

修饰符作用范围示例
public默认,所有地方可访问public name: string
private仅类内部可访问private secret: string
protected类内部及子类可访问protected familyName: string
readonly只读(不能重新赋值,可结合以上)readonly id: number
class Employee {
  constructor(
    public name: string,
    private salary: number,
    protected department: string,
    readonly id: number
  ) {}

  getInfo() {
    console.log(this.salary);      // OK
    console.log(this.department);  // OK
  }
}

class Manager extends Employee {
  manage() {
    // console.log(this.salary);    // 错误:private
    console.log(this.department);  // OK:protected
  }
}

3. 静态成员(Static Members)

属于类本身,而不是实例:

class MathUtils {
  static PI: number = 3.14159;

  static circleArea(radius: number): number {
    return this.PI * radius ** 2;
  }
}

console.log(MathUtils.PI);           // 3.14159
console.log(MathUtils.circleArea(5)); // 通过类名调用

4. 类继承(Extends)与 super

class Animal {
  constructor(public name: string) {}

  move(distance: number = 0) {
    console.log(`${this.name} moved ${distance}m.`);
  }
}

class Dog extends Animal {
  constructor(name: string, public breed: string) {
    super(name);  // 必须调用 super()
  }

  bark() {
    console.log("Woof!");
  }

  move(distance: number = 5) {
    super.move(distance);  // 调用父类方法
    console.log("Dog is running!");
  }
}

let dog = new Dog("Buddy", "Golden");
dog.bark();
dog.move();  // 先调用 Animal.move,再输出 "Dog is running!"

5. 抽象类(Abstract Class)

不能直接实例化,用于定义子类必须实现的成员:

abstract class Shape {
  abstract getArea(): number;  // 抽象方法,必须在子类实现

  move(x: number, y: number) {
    console.log(`Moved to (${x}, ${y})`);
  }
}

class Circle extends Shape {
  constructor(public radius: number) {
    super();
  }

  getArea(): number {
    return Math.PI * this.radius ** 2;
  }
}

let circle = new Circle(10);
console.log(circle.getArea());
// let shape = new Shape();  // 错误:不能实例化抽象类

6. 类实现接口(Implements)

类可以实现一个或多个接口:

interface Printable {
  print(): void;
}

interface Loggable {
  log(message: string): void;
}

class Document implements Printable, Loggable {
  constructor(public title: string) {}

  print() {
    console.log(`Printing ${this.title}`);
  }

  log(message: string) {
    console.log(`[${this.title}] ${message}`);
  }
}

7. getter / setter

class Rectangle {
  constructor(private _width: number, private _height: number) {}

  get area(): number {
    return this._width * this._height;
  }

  set width(value: number) {
    if (value <= 0) throw new Error("宽度必须正数");
    this._width = value;
  }
}

let rect = new Rectangle(10, 5);
console.log(rect.area);  // 50(调用 getter)
rect.width = 20;         // 调用 setter

8. 类作为类型使用

class Car {
  constructor(public brand: string) {}
}

let myCar: Car = new Car("Tesla");
function drive(vehicle: Car) {
  console.log(`Driving ${vehicle.brand}`);
}

9. 装饰器(Decorators)—— 实验性特性(需启用 experimentalDecorators

常用于框架(如 Angular、NestJS):

function sealed(target: Function) {
  Object.seal(target);
  Object.seal(target.prototype);
}

@sealed
class Greeter {
  greeting: string;
  constructor(message: string) {
    this.greeting = message;
  }
}

10. 最佳实践建议

建议说明
使用参数属性简写减少 constructor 冗余
优先使用 privatereadonly封装性更好
抽象类用于定义通用行为强制子类实现关键方法
接口 + 类组合使用接口定义合约,类实现细节
静态成员用于工具方法/常量如配置、工厂方法
开启 strictPropertyInitialization强制非 undefined 属性在 constructor 初始化

小结:类特性速查表

特性语法示例
基本类class Person { constructor(public name: string) {} }
访问修饰符private age: number
静态成员static count: number = 0
继承class Dog extends Animal {}
抽象类/方法abstract class Shape { abstract draw(): void; }
实现接口class User implements Printable {}
getter/setterget fullName(): string { return ... }

TypeScript 的类系统结合了现代 JS 的灵活性和强类型检查,是构建大型、可维护应用的核心工具,尤其在 Angular、NestJS 等框架中广泛使用。

如果您想深入某个部分(如泛型类装饰器实战类与模块的结合、或设计模式实现),请告诉我!

文章已创建 3383

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部