返回

TypeScript的类与ES6的类:亲密关系却各有各的魅力

前端

TypeScript的类与ES6的类有着亲密的关系,因为TypeScript的类是基于ES6的类的。虽然如此,两者的差异体现在方方面面。

类的声明

ES6中类的声明非常简洁。让我们看一个例子:

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  getName() {
    return this.name;
  }

  getAge() {
    return this.age;
  }
}

TypeScript中类的声明与ES6基本一致。唯一的区别是,TypeScript中的类必须使用class来声明。

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

  getName(): string {
    return this.name;
  }

  getAge(): number {
    return this.age;
  }
}

成员修饰符

ES6中类的成员变量和成员方法可以使用以下修饰符:

  • public:公开的,可以在类的内部和外部访问
  • private:私有的,只能在类的内部访问
  • protected:受保护的,只能在类的内部和子类中访问

TypeScript中的类成员可以使用以下修饰符:

  • public:公开的,可以在类的内部和外部访问
  • private:私有的,只能在类的内部访问
  • protected:受保护的,只能在类的内部和子类中访问
  • readonly:只读的,只能在类的内部赋值,之后不能再修改

类的继承

ES6中类的继承使用extends关键字。例如:

class Employee extends Person {
  constructor(name, age, salary) {
    super(name, age);
    this.salary = salary;
  }

  getSalary() {
    return this.salary;
  }
}

TypeScript中的类的继承与ES6基本一致。唯一的区别是,TypeScript中的类必须使用关键字class来声明。

class Employee extends Person {
  constructor(name: string, age: number, salary: number) {
    super(name, age);
    this.salary = salary;
  }

  getSalary(): number {
    return this.salary;
  }
}

多态

多态是面向对象编程中的一项重要特性。它允许子类对象以不同的方式响应相同的调用。在ES6和TypeScript中,多态都是通过方法重写来实现的。

例如,以下代码演示了如何在TypeScript中实现多态:

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

  getName(): string {
    return this.name;
  }

  getAge(): number {
    return this.age;
  }
}

class Employee extends Person {
  constructor(name: string, age: number, salary: number) {
    super(name, age);
    this.salary = salary;
  }

  getSalary(): number {
    return this.salary;
  }
}

class Student extends Person {
  constructor(name: string, age: number, major: string) {
    super(name, age);
    this.major = major;
  }

  getMajor(): string {
    return this.major;
  }
}

function printPersonInfo(person: Person) {
  console.log(`Name: ${person.getName()}`);
  console.log(`Age: ${person.getAge()}`);
}

const employee = new Employee("John Doe", 30, 100000);
const student = new Student("Jane Doe", 20, "Computer Science");

printPersonInfo(employee);
printPersonInfo(student);

输出:

Name: John Doe
Age: 30
Name: Jane Doe
Age: 20

TypeScript 的类,灵活而强大。它们帮助程序员创建可重用、可维护的代码,简化了编程任务。

TypeScript 的类特有的特性

除了与 ES6 的类共有的特性外,TypeScript 的类还有一些特有的特性:

  • 接口实现:TypeScript 的类可以实现接口。接口是一种契约,它定义了类必须实现的方法和属性。
  • 抽象类:TypeScript 中的类可以被声明为抽象类。抽象类不能被实例化,它只能被子类继承。
  • 泛型:TypeScript 中的类可以是泛型的。泛型类允许你在定义类时使用类型参数。
  • 存取器:TypeScript 中的类可以定义存取器。存取器允许你以属性的方式访问类的方法。