In this article, I am going to create a class with a constructor which will accept three parameters and then print them on the screen.
First of all, I need to create an interface that will get extended by the class later on!
interface IComputer { brand : string | undefined; user? : string | undefined; year? : number | undefined; showBrand() : void; }
The user and the year parameters of the interface are optional and the class which extends the interface does not need to implement them. This interface also has one method which will get implemented by the class later to print the outcome on the screen.
class Computer implements IComputer { public brand : string; public user : string; public year : number; constructor(brand : string, user : string, year : number ) { this.brand = brand this.user = user this.year = year } showBrand() : void { 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}`) } }
As you can see the class has implemented the interface and the class has a constructor which will be called upon initiated and set those parameters accordingly.
Now here is how to create the class object and assigned those parameters to the class variables:
let computer = new Computer("Dell", "localhost", 2022);
After that, I can call the class method to print the outcome on the screen.
computer.showBrand()
Which will then display the below message:
The brand of this pc is Dell and the name of this pc is localhost and its year is 2022