返回

超越你的眼界,领略TypeScript对象之美

前端

  1. TypeScript对象的基石:类型系统

TypeScript是一门强类型语言,这意味着在编译时,它会检查变量和表达式的类型是否匹配。这有助于及早发现错误,提高代码的可靠性。

TypeScript的对象类型由属性类型和方法类型组成。属性类型定义了对象的属性可以存储什么类型的值,方法类型定义了对象的函数可以接收什么类型的参数并返回什么类型的值。

例如,以下代码定义了一个名为Person的接口,它包含了name属性和greet方法:

interface Person {
  name: string;
  greet(message: string): string;
}

您可以使用Person接口来定义一个对象类型,如下所示:

const person: Person = {
  name: "John Doe",
  greet(message: string): string {
    return `Hello, ${message}!`;
  }
};

2. 继承:让对象站在巨人的肩膀上

TypeScript支持单继承,这意味着一个类只能从另一个类继承。子类继承父类的所有属性和方法,并可以定义自己的属性和方法。

例如,以下代码定义了一个名为Employee的类,它从Person类继承:

class Employee extends Person {
  jobTitle: string;

  constructor(name: string, jobTitle: string) {
    super(name);
    this.jobTitle = jobTitle;
  }

  greet(message: string): string {
    return `Hello, ${message}! I'm an employee.`;
  }
}

现在,您可以创建一个Employee对象,并使用继承的属性和方法:

const employee = new Employee("John Doe", "Software Engineer");
console.log(employee.name); // "John Doe"
console.log(employee.jobTitle); // "Software Engineer"
console.log(employee.greet("World")); // "Hello, World! I'm an employee."

3. 多态:让对象翩翩起舞

多态性是指对象能够以不同的方式响应相同的调用。例如,Person类的greet方法可以被不同的Person对象以不同的方式实现。

以下代码演示了多态性的魅力:

const person1 = new Person();
const employee1 = new Employee("John Doe", "Software Engineer");

const greetAll = (people: Person[]) => {
  for (const person of people) {
    console.log(person.greet("World"));
  }
};

greetAll([person1, employee1]);

输出结果如下:

Hello, World!
Hello, World! I'm an employee.

4. 抽象类:勾勒对象的蓝图

抽象类是不能被实例化的类。它定义了子类必须实现的属性和方法,但它本身不能被用来创建对象。

抽象类通常用于定义通用接口或抽象概念。例如,以下代码定义了一个名为Shape的抽象类,它定义了draw方法,但没有实现它:

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

您不能创建一个Shape对象,但您可以创建子类来实现draw方法。例如,以下代码定义了一个名为Rectangle的类,它继承自Shape类:

class Rectangle extends Shape {
  width: number;
  height: number;

  constructor(width: number, height: number) {
    super();
    this.width = width;
    this.height = height;
  }

  draw(): void {
    console.log(`Drawing a rectangle with width ${this.width} and height ${this.height}`);
  }
}

现在,您可以创建一个Rectangle对象,并调用draw方法:

const rectangle = new Rectangle(10, 20);
rectangle.draw(); // "Drawing a rectangle with width 10 and height 20"

5. 接口:定义对象的契约

接口是定义对象属性和方法的契约。接口本身不包含任何实现,它只是定义了对象应该具有的属性和方法。

接口通常用于定义函数的参数类型和返回值类型。例如,以下代码定义了一个名为Drawable的接口,它定义了draw方法:

interface Drawable {
  draw(): void;
}

您可以使用Drawable接口来定义一个函数的参数类型,如下所示:

function drawAll(shapes: Drawable[]) {
  for (const shape of shapes) {
    shape.draw();
  }
}

现在,您可以传递任何实现了Drawable接口的对象给drawAll函数,例如:

drawAll([rectangle, new Circle(5)]);

6. 修饰符:控制对象的可