Below is an example of implementing the interface in TypeScript. Let’s say you have an IComputer interface as follows:-
interface IComputer { brand : string | undefined; user? : string | undefined; year? : number | undefined; showBrand() : void; }
The above interface has three variables, two are optional variables that a class does not need to implement if it does not want to. The undefined type is used in that class to avoid errors if that class does not declare that variable within its constructor. Below is how that class implements the above interface.
class Computer implements IComputer { brand : string | undefined; user : string | undefined; year : number | undefined; 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}`) } }
Now you can create that class object and declare its variables and then print the brand, user name, and the year of that computer object as follows:-
let computer = new Computer(); computer.brand = "Dell"; computer.user = "localhost" computer.year = 2022 computer.showBrand()
The outcome is as follows:-
The brand of this pc is Dell and the name of this pc is localhost and its year is 2022
You can ignore the user and the year variables because they are optional but in this case, I am declaring them as well!