An
TypeScript provides to create the interfaces by the keyword
Below is the example of the interface.
In the below example we are creating two classes Customer and Employee which are implementing the IUser interface, created above.
interface
is the abstract type of structure which allows defining some set of properties or behavior that a class must implement. To define a signature and use it to across the objects we create an interface.TypeScript provides to create the interfaces by the keyword
interface
Below is the example of the interface.
interface IUser{
name:string;
age:number;
sayHello :()=string
}
Now we can implement this interface to our class by the below convention:class [ClassName] implements [InterfaceName]
In the below example we are creating two classes Customer and Employee which are implementing the IUser interface, created above.
class Customer implements IUser {
custID: string;
name: string;
age: number;
constructor (custID: string, name: string, age: number) {
this.custID = custID;
this.name = name;
this.age = age;
}
sayHello () {
console.log(`Hello, I am customer, My name is ${name}, my id is ${custID} and my age is ${age}`);
}
}
class Employee implements IUser {
empID: string;
name: string;
age: number;
constructor (empID: string, name: string, age: number) {
this.empID = empID;
this.name = name;
this.age = age;
}
sayHello () {
console.log(`Hello, I am employee, My name is ${name}, my id is ${empID} and my age is ${age}`);
}
}
After creating the classes, Let's create the instaces of both the classes;.
let emp:IUser = new Employee("EMP001", "John", 30);
let cust:IUser = new Employee("CUST001", "Bob", 41);
Now call the sayHello() function for both the instaces.
emp.sayHello(); //Output: Hello, My name is John, my id is EMP001 and my age is 30
cust.sayHello(); //Output: Hello, My name is Bob, my id is CUST001 and my age is 41
No comments
Post your comment.