Skip to content

TypeScript 类是面向对象编程(OOP)的一种重要概念。类是一组数据和函数的集合,它们一起封装了数据和行为。类可以用来创建对象,这些对象具有状态和行为。

类的定义

TypeScript 类定义语法如下:

typescript
class Person {
    name: string;
    age: number;

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

    greet() {
        console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
    }
}

继承

TypeScript 类可以继承其他类,通过 extends 关键字实现。

typescript
class Student extends Person {
    grade: number;

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

    study() {
        console.log(`${this.name} is studying in grade ${this.grade}.`);
    }
}

公共、私有与受保护的修饰符

typescript
class Animal {
    public name: string;
    private _type: string;
    protected color: string;

    constructor(name: string, type: string, color: string) {
        this.name = name;
        this._type = type;
        this.color = color;
    }

    get type() {
        return this._type;
    }

    set type(value: string) {
        this._type = value;
    }
}

class Dog extends Animal {
    bark() {
        console.log(`${this.name} barks.`);
    }
}

const dog = new Dog('Rufus', 'Golden Retriever', 'Brown');
dog.bark(); // Rufus barks.
console.log(dog.type); // Golden Retriever
dog.type = 'Labrador Retriever';
console.log(dog.type); // Labrador Retriever

存取器 (get 和 set)

typescript
class Car {
    private _make: string;
    private _model: string;

    constructor(make: string, model: string) {
        this._make = make;
        this._model = model;
    }

    get make() {
        return this._make;
    }

    set make(value: string) {
        this._make = value;
    }

    get model() {
        return this._model;
    }

    set model(value: string) {
        this._model = value;
    }
}

const car = new Car('Toyota', 'Corolla');
console.log(car.make); // Toyota
console.log(car.model); // Corolla
car.make = 'Honda';
car.model = 'Civic';
console.log(car.make); // Honda
console.log(car.model); // Civic

静态属性

typescript
class MathHelper {
    static PI: number = 3.14159;

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

console.log(MathHelper.PI); // 3.14159
console.log(MathHelper.calculateCircumference(5)); // 31.4159

抽象类

typescript
abstract class Shape {
    abstract draw(): void;
}

class Circle extends Shape {
    draw() {
        console.log('Drawing a circle.');
    }
}

class Rectangle extends Shape {
    draw() {
        console.log('Drawing a rectangle.');
    }
}

const circle = new Circle();
circle.draw(); // Drawing a circle.

const rectangle = new Rectangle();
rectangle.draw(); // Drawing a rectangle.