TypeScript中的类
本文介绍了TypeScript中的类。
YouTube Video
TypeScript中的类
TypeScript中的类基于JavaScript的ES6类,并提供了类型注解和访问修饰符等附加功能。这使您能够利用面向对象编程的概念,同时确保更强大和清晰的类型安全性。
以下是对TypeScript中类的基本用法和功能的说明。
基本类的定义
1class Person {
2 name: string; // Member variable
3 age: number; // Member variable
4
5 // Constructor
6 constructor(name: string, age: number) {
7 this.name = name;
8 this.age = age;
9 }
10
11 // Method
12 greet(): void {
13 console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
14 }
15}
16
17const person = new Person("Alice", 25);
18person.greet(); // Hello, my name is Alice and I am 25 years old.
name和age是该类的属性(成员变量)。constructor是创建类实例时调用的方法,它接受参数并将值分配给属性。greet是类的方法,表示其没有返回值,其类型为void。
访问修饰符
在TypeScript中,您可以使用访问修饰符(public、private、protected)来控制对类属性和方法的访问。
public
默认情况下,所有属性和方法都是public的。这意味着可以从类外部访问它们。
1class Animal {
2 public species: string;
3
4 constructor(species: string) {
5 this.species = species;
6 }
7
8 public makeSound(): void {
9 console.log(`${this.species} makes a sound.`);
10 }
11}
12
13const animal = new Animal("Dog");
14console.log(animal.species); // Dog
15animal.makeSound(); // Dog makes a sound.
species属性和makeSound方法被声明为public,可以从类外部访问。
private
使用private修饰符可以防止从类外部访问属性或方法。
1class Car {
2 private brand: string;
3
4 constructor(brand: string) {
5 this.brand = brand;
6 }
7
8 public getBrand(): string {
9 return this.brand;
10 }
11}
12
13const car = new Car("Toyota");
14// console.log(car.brand); // Error: 'brand' is private and cannot be accessed.
15console.log(car.getBrand()); // Toyota
brand属性被声明为private,因此无法从类外部访问。- 通过使用
private修饰符隐藏属性,可以实现数据的封装。
protected
protected修饰符限制了从类外部的访问,但允许子类(派生类)访问。
1class Vehicle {
2 protected model: string;
3
4 constructor(model: string) {
5 this.model = model;
6 }
7}
8
9class Truck extends Vehicle {
10 public getModel(): string {
11 return this.model;
12 }
13}
14
15const truck = new Truck("Ford F-150");
16console.log(truck.getModel()); // Ford F-150
17
18// console.log(truck.model);
19// Error: Property 'model' is protected and only accessible within class 'Vehicle' and its subclasses.
model属性被声明为protected,因此无法从类外部访问,但可以在子类中访问。
Getter和Setter
在TypeScript中,您可以使用get和set关键字定义getter和setter,以获取和设置属性值。
1class Employee {
2 private _salary: number;
3
4 constructor(salary: number) {
5 this._salary = salary;
6 }
7
8 // Getter
9 get salary(): number {
10 return this._salary;
11 }
12
13 // Setter
14 set salary(newSalary: number) {
15 if (newSalary > 0) {
16 this._salary = newSalary;
17 } else {
18 console.log("Salary must be positive.");
19 }
20 }
21}
22
23const employee = new Employee(50000);
24console.log(employee.salary); // 50000
25employee.salary = 60000;
26console.log(employee.salary); // 60000
27employee.salary = -100; // Salary must be positive.
- 在这个例子中,
salary属性使用了getter和setter来控制外部的访问和更新。setter方法会进行校验以防止负值输入,如果提供了无效的值,则会显示警告信息。
继承
在TypeScript中,类可以被继承。使用extends关键字,您可以继承父类的功能。
1class Animal {
2 constructor(public name: string) {}
3
4 public move(): void {
5 console.log(`${this.name} is moving.`);
6 }
7}
8
9class Bird extends Animal {
10 public fly(): void {
11 console.log(`${this.name} is flying.`);
12 }
13}
14
15const bird = new Bird("Sparrow");
16bird.move(); // Sparrow is moving.
17bird.fly(); // Sparrow is flying.
- 在这个例子中,
Bird类继承自Animal类,因此它可以使用Animal类的move方法。此外,它还定义了自己的fly方法,在继承父类功能的同时增加了新功能。
抽象类
抽象类(abstract)不能直接实例化,通常用作模板以在子类中提供具体实现。
1abstract class Shape {
2 abstract getArea(): number;
3
4 public describe(): void {
5 console.log("This is a shape.");
6 }
7}
8
9class Circle extends Shape {
10 constructor(private radius: number) {
11 super();
12 }
13
14 public getArea(): number {
15 return Math.PI * this.radius * this.radius;
16 }
17}
18
19const circle = new Circle(5);
20console.log(circle.getArea()); // 78.53981633974483
21circle.describe(); // This is a shape.
- 在这个例子中,
Shape被定义为抽象类,getArea是一个抽象方法,必须由子类实现。Circle类继承了这个抽象类,并实现了自己的getArea方法用于计算圆的面积。此外,像describe这样具体的方法被作为通用功能继承,可以直接使用。
与接口的关系
类可以实现接口,确保类具有特定的属性和方法。
1interface Flyable {
2 fly(): void;
3}
4
5class Airplane implements Flyable {
6 public fly(): void {
7 console.log("The airplane is flying.");
8 }
9}
10
11const airplane: Flyable = new Airplane();
12airplane.fly(); // The airplane is flying.
- 在这个例子中,
Flyable接口定义了fly方法的规范,Airplane类通过为fly方法提供具体实现来实现该接口。通过这种方式,任何可以被视为Flyable类型的对象都保证拥有fly方法。
静态成员
当你在类中定义静态成员时,这些方法和属性是与类本身相关联的。静态成员可以在不实例化类的情况下调用。
1class MathUtils {
2 static PI: number = 3.14;
3
4 static add(a: number, b: number): number {
5 return a + b;
6 }
7}
8
9console.log(MathUtils.add(10, 20)); // 30
10console.log(MathUtils.PI); // 3.14
- 你可以使用
static关键字来定义静态方法。 - 在这个例子中,
MathUtils类定义了静态方法add和静态属性PI。 - 静态成员不属于类的实例,而是可以直接通过类本身调用。
总结
TypeScript 类为 JavaScript 类功能添加了类型安全、访问修饰符和抽象类等功能。这使得面向对象编程更加强大和安全。
您可以在我们的YouTube频道上使用Visual Studio Code跟随上述文章进行学习。 请也查看我们的YouTube频道。