面试题-TS(四):如何在 TypeScript 中使用类和继承?
发布人:shili8
发布时间:2025-03-04 06:37
阅读次数:0
**面试题-TS(四):如何在TypeScript中使用类和继承**
在TypeScript中,类是构建复杂对象的基本单位。继承机制允许我们创建一个新类,基于已有的类,这样我们就可以重用已有的代码并添加新的功能。
**类定义**
在TypeScript中,我们使用`class`关键字来定义一个类。例如:
typescriptclass Person { private name: string; private age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } public sayHello(): void { console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); } }
在这个例子中,我们定义了一个`Person`类,它有两个私有属性:`name`和`age`。我们还定义了一个构造函数(constructor),用于初始化这些属性。最后,我们定义了一个方法`sayHello()`,它会输出一条信息。
**继承**
继承是TypeScript中非常重要的概念。通过继承,我们可以创建一个新类,基于已有的类。这有助于我们重用已有的代码并添加新的功能。
例如:
typescriptclass Student extends Person { private studentId: number; constructor(name: string, age: number, studentId: number) { super(name, age); // 调用父类的构造函数 this.studentId = studentId; } public sayHello(): void { console.log(`Hello, my name is ${this.name} and I am ${this.age} years old. My student ID is ${this.studentId}.`); } }
在这个例子中,我们定义了一个`Student`类,它继承自`Person`类。我们通过使用`extends`关键字来指定继承关系。在构造函数中,我们调用父类的构造函数(super())来初始化父类的属性。
**多态**
多态是指同一个方法在不同类中的行为可能会有所不同。这是一个非常重要的概念,因为它允许我们写出更灵活和更易维护的代码。
例如:
typescriptclass Animal { public sound(): void { console.log("The animal makes a sound."); } } class Dog extends Animal { public sound(): void { console.log("The dog barks."); } } class Cat extends Animal { public sound(): void { console.log("The cat meows."); } }
在这个例子中,我们定义了一个`Animal`类,它有一个方法`sound()`。我们还定义了两个子类:`Dog`和`Cat`,它们分别重写了父类的`sound()`方法。
**总结**
在TypeScript中,类是构建复杂对象的基本单位。继承机制允许我们创建一个新类,基于已有的类,这样我们就可以重用已有的代码并添加新的功能。多态是指同一个方法在不同类中的行为可能会有所不同。这是一个非常重要的概念,因为它允许我们写出更灵活和更易维护的代码。
**参考**
* TypeScript官方文档: />* TypeScript Handbook: