In this TypeScript class inheritance example, I am going to create a subclass that inherits from the main base class as follows:-
1) Create the interface which will be implemented by the Computer class.
interface IComputer { brand : string | undefined; user? : string | undefined; year? : number | undefined; showBrand(password : string) : void; }
Create the Computer main class which implements the above interface.
class Computer implements IComputer { public brand : string; public user : string; public year : number; private password : string = "seriously"; static count : number = 0; constructor(brand : string, user : string, year : number ) { this.brand = brand this.user = user this.year = year } public updatePassword() : void { Computer.count++; console.log(`Update password : ${Computer.count} time(s)`) } public showBrand(password : string) : void { if(password == this.password) { console.log(`The brand of this pc is ${this.brand} and the name of this pc is ${this.user} and its year is ${this.year}`) } else { console.log("The password does not match!") } } set reset(password : string) { this.password = password } get reset() : string { return this.password } }
At last, create the subclass which inherits the base class.
class Computer1 extends Computer { public updatePassword(): void { super.updatePassword(); console.log("Hello World!"); } }
Next, run the below commands:-
let computer = new Computer("Dell", "localhost", 2022); computer.reset = "aeiou" computer.updatePassword() computer.showBrand("pick") computer.showBrand(computer.reset) let computer1 = new Computer1("Acer", "localhost1", 2022) computer1.reset = "aeioq" computer1.updatePassword() computer1.showBrand(computer1.reset)
That will result in below outcomes:-
Update password : 1 time(s) The password does not match! The brand of this pc is Dell and the name of this pc is localhost and its year is 2022 Update password : 2 time(s) Hello World! The brand of this pc is Acer and the name of this pc is localhost1 and its year is 2022
As you all can see that there is no need to create the constructor within the Computer1 class again which will use the constructor of the base class to receive the input parameters.