- Learning TypeScript 2.x
- Remo H. Jansen
- 221字
- 2025-04-04 17:02:05
Depth of the inheritance tree (DIT)
We can also declare a new class that inherits from a class, which is already inheriting from another class. In the following code snippet, we declare a class called SchoolPrincipal that extends the Teacher class, which extends the Person class:
class SchoolPrincipal extends Teacher { public manageTeachers() { return console.log( `We need to help our students!` ); } }
If we create an instance of the SchoolPrincipal class, we will be able to access all the properties and methods from its parent classes (SchoolPrincipal, Teacher, and Person):
const principal = new SchoolPrincipal( "Remo", "Jansen", "remo.jansen@wolksoftware.com" ); principal.greet(); // "Hi!" principal.teach(); // "Welcome to class!" principal.manageTeachers(); // "We need to help our students!"
Unfortunately, we don't have a specific rule that we can follow when we are unsure whether we should increase the depth of the inheritance tree (DIT).
We should use inheritance in such a way that it helps us to reduce the complexity of our application and not the opposite. We should try to keep the DIT between zero and four because a value greater than four would compromise encapsulation and increase complexity.