如何在 TypeScript 中继承类 - TypeScript 入门教程





5.00/5 (3投票s)
在本 TypeScript 教程系列的文章中,我们将学习如何继承一个 TypeScript 类。请继续阅读,今天就来学习它。
就像任何其他支持面向对象编程 (OOP) 的语言一样,TypeScript 也允许你继承一个基类。在上一篇文章中,我们学习了 如何在 TypeScript 中创建类。我们还学习了如何创建构造函数以及如何实例化类对象。
在本 TypeScript 教程系列的文章中,我们将学习如何继承一个 TypeScript
类。请继续阅读,今天就来学习它。
TypeScript 中的继承
在 TypeScript 中,你可以从另一个类继承一个类。只需使用 extends
关键字即可执行继承。考虑以下示例以更好地理解它
class Person {
// properties
firstName: string;
lastName: string;
// constructor
constructor (fName: string, lName: string) {
// fill the properties
this.firstName = fName;
this.lastName = lName;
}
// method
getFullName() {
return `${firstName} ${lastName}`;
}
}
class Employee extends Person {
// properties
empID: string;
designation: string;
// constructor
constructor (fName: string, lName: string,
eID: string, desig: string) {
// call the base class constructor
super(fName, lName);
// fill the other properties
this.empID = eID;
this.designation = desig;
}
// method
toString() {
return `${empID} - ${firstName} ${lastName}
=> ${designation}`;
}
}
这里,Employee
类通过编写 class Employee extends Person
从其基类 Person
继承。在派生类中,可以使用 super(...)
来调用基类的构造函数。例如,Employee
类构造函数中的 super(fName, lName)
通过传递参数值 fName
和 lName
来调用基类构造函数。
现在,在以下代码片段中,我们创建了 Employee
类的实例,并将其构造函数传递了四个参数。在 Employee
类构造函数的实现中,我们调用了基类构造函数以传递员工的姓和名。因此,当你调用派生类的 toString()
方法时,它将打印出这两个属性。
let employee: Employee = new Employee("Kunal",
"Chowdhury",
"EMP001022",
"Software Engineer"
);
console.log(employee.toString());
摘要
让我们总结一下今天所学的内容。我们学习了如何使用 extends
关键字在 TypeScript 中从基类继承一个类。然后,我们讨论了如何通过传递相应的值来调用基类构造函数。在 本教程系列的下一篇文章中,我们将讨论接口。在此之前,祝你学习愉快!