Posted on January 7, 2023
Inheritance is the basic concept that comes from the object-oriented programming language. Inheritance in TypeScript works in the same way as any other programming language because TypeScript is also an object-oriented language. In Inheritance, we have two concepts which are known as parent class and child class. In Inheritance, we inherit the properties of the superclass, which is termed a parent class, and the one which is inheriting the superclass is called a child class; this is the basic concept of inheritance in any programming language. JavaScript uses prototypal inheritance, not classical inheritance like Java or C#. ES6 introduces the class syntax that is simply the syntactic sugar of the prototypal inheritance. TypeScript supports inheritance like ES6. Suppose you have the following To inherit a class, you use the Because the To call the constructor of the parent class in the constructor of the child class, you use the Here is the full code in GitHub to play https://github.com/engg-aruny/AngularQuickTips Use the Use Introduction to the TypeScript inheritance
Animal
class:class Animal {
age: number;
breed: string;
constructor(age: number, breed: string) {
this.age = age;
this.breed = breed;
}
makeSound(sound: string): void {
console.log(sound);
}
}
extends
keyword. For example, the following Dog
class inherits the Animal
class:class Dog extends Animal {
ownerName: string;
constructor(age: number, breed: string, ownerName: string) {
super(age, breed) // call parent constructor
this.ownerName = ownerName
}
makeSound(): void {
super.makeSound("woof woof");
}
getAge(): number {
return this.age * 7;
}
}
Constructor
Animal
class has a constructor that initializes the age
and breed
properties, you need to initialize these properties in the constructor of the Dog class by calling its parent class constructor.super()
syntax. For example:class Animal {
age: number;
breed: string;
constructor(age: number, breed: string) {
this.age = age;
this.breed = breed;
}
makeSound(sound: string): void {
console.log(sound);
}
}
class Dog extends Animal {
ownerName: string;
constructor(age: number, breed: string, ownerName: string) {
super(age, breed) // call parent constructor
this.ownerName = ownerName
}
makeSound(): void {
super.makeSound("woof woof");
}
getAge(): number {
return this.age * 7;
}
}
class Cat extends Animal {
constructor(age: number, breed: string) {
super(age, breed)
}
makeSound(): void {
super.makeSound('meow meow');
}
}
Summary
extends
keyword to allow a class to inherit from another class.
super()
in the constructor of the child class to call the constructor of the parent class.