TypeScript的类与接口(Interfaces)
在前面的几篇文章中,我们探讨了TypeScript的基本特性和数据类型系统。本文将重点介绍TypeScript中的类(Class)和接口(Interface),这两个概念是面向对象编程的核心,它们为代码的结构化和模块化提供了强大的工具。
类(Class)
在TypeScript中,类是创建对象的蓝图。它允许你定义属性和方法,并控制对这些属性和方法的访问。
使用类
类可以包含构造函数、属性、方法和访问修饰符。
class Car {
brand: string;
constructor(brand: string) {
this.brand = brand;
}
drive() {
console.log(`The car is driving. Brand: ${this.brand}`);
}
}
let myCar = new Car('Tesla');
myCar.drive(); // 输出: The car is driving. Brand: Tesla
在这个例子中,我们定义了一个Car
类,它有一个brand
属性和一个drive
方法。
访问修饰符
TypeScript中的访问修饰符包括public
、private
和protected
。
public
: 公开的,可以在任何地方访问。private
: 私有的,只能在类的内部访问。protected
: 受保护的,可以在类、子类和继承类中访问。
class Person {
private name: string;
constructor(name: string) {
this.name = name;
}
public sayHello() {
console.log(`Hello, my name is ${this.name}`);
}
// 子类中可以访问 protected 成员
protected getAge() {
return 30;
}
}
let person = new Person('Kimi');
person.sayHello(); // 输出: Hello, my name is Kimi
console.log(person.getAge()); // 输出: 30
接口(Interface)
接口在TypeScript中是一种定义契约的方式,它规定了类应该具有哪些属性和方法,但不定义这些属性和方法的具体实现。
使用接口
接口可以用来定义对象的形状,类可以实现一个或多个接口。
interface Shape {
color: string;
area: number;
}
class Circle implements Shape {
color: string;
radius: number;
constructor(radius: number, color: string) {
this.radius = radius;
this.color = color;
this.area = Math.PI * this.radius * this.radius;
}
}
let myCircle = new Circle(5, 'blue');
console.log(myCircle.area); // 输出: 78.53975
在这个例子中,Shape
接口定义了color
和area
属性,Circle
类实现了这个接口。
接口与类的结合
接口可以与类结合使用,为类的实例提供额外的类型检查。
interface PersonInterface {
name: string;
age: number;
sayHello(): void;
}
class Person implements PersonInterface {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
let myPerson = new Person('Kimi', 30);
myPerson.sayHello(); // 输出: Hello, my name is Kimi and I am 30 years old.
在这个例子中,Person
类实现了PersonInterface
接口,确保了类的实例具有接口定义的所有属性和方法。
结语
通过本文的介绍,我们深入了解了TypeScript中的类和接口。类是创建对象的模板,而接口定义了对象应该具有的结构。这两个概念在面向对象编程中非常重要,它们帮助我们创建结构化和模块化的代码。在后续的文章中,我们将继续探索TypeScript的其他特性,如泛型、装饰器等,并提供实际的代码示例和最佳实践。