Course Banner


Typescript Interfaces

An interface is a proforma, a format that the implementing entity should agree to conform to that proforma.

In interface,we define properties, methods, and events, which are the members of the interface.One very important thing which you should bear in mind is that   interfaces just define the properties but it is implemented by the other those classes or interfaces which implements it in declaration. The benefit is that It often helps in providing a standard structure that the deriving classes would follow.

As you know Typescript does not allow multiple inheritance, but it's possible to do the same through interfaces.

Declaring Interfaces

Just like class, interface keyword is used to declare interface. Here is the syntax to declare an interface −

Syntax

interface interface_name {


}

Example :


Let’s say for example that we have the following code where we define two employee departments. One is sales and other one is customer support of the same company.


const sales= {

 empId: 1,

 firstName: 'Rajesh',

 lastName: 'Kumar',

 House: false,

 email: 'rajesh@gmail.com'

}


const customerSupport = {

 firstName: 'Anju',

 lastName: 'Patel',

 House: true,

 email: 'anju@gmail.com'

}


As you can see in the above two objects, most of the fields are same. So, why not make a contract so that our employee objects respect a specified type definition:


interface Employee {

 id: number;

 firstName: string;

 lastName: string;

 Hose: boolean;

 email: string;

}


We have just declared the interface and actual use will be later.


const sales: Employee = {

 id: 1,

 firstName: 'Rajesh',

 lastName: 'Kumar',

 house: false,

 email: 'rajesh@gmail.com'

}


const customerSupport: Employee = {

 id: 2,

 firstName: 'Anju',

 lastName: 'Patel',

 house: true,

 email: 'anju@gmail.com'

}


Suppose we try to define Employee objects with missing properties, additional information with properties of the wrong type, the TypeScript compiler will throw and error.


But typescript provides flexibility for that  in your interfaces with the Elvis (Optional )operator (?):


interface Employee {

 id: number;

 firstName: string;

 lastName: string;

 house: boolean;

 email: string;

 car?: string;

}



const sales: Employee = {

 id: 1,

 firstName: 'Rajesh',

 lastName: 'Kumar',

 house: false,

 email: 'rajesh@gmail.com'

}


const customerSupport: Employee = {

 id: 2,

 firstName: 'Anju',

 lastName: 'Patel',

 house: true,

 email: 'anju@gmail.com'

 car:’Yes’

}



In the above code you can see that we did not define car for Rajesh but we have defined for Anju. Since that was an optional field, thats why TypeScript did not complain.


Your interfaces can be defined in their own files, and then imported with the ES6 module syntax. You will be using this kind of syntax in Angular learning.


import { Employee } from '../interfaces/Employee;


const sales: Employee = {

 id: 1,

 firstName: 'Rajesh',

 lastName: 'Kumar',

 house: false,

 email: 'rajesh@gmail.com'

}


const customerSupport: Employee = {

 id: 2,

 firstName: 'Anju',

 lastName: 'Patel',

 house: true,

 email: 'anju@gmail.com'

 car:’Yes’

}



Class and Interfaces Example :


interface Car {

 color:string

}


class Mercedez implements Car {

 color:string

 computerized:string

 constructor(color:string,computerized:string) {

    this.color = color

    this.computerized = computerized

 }

}


var obj = new Mercedez('Red','Yes')


console.log("Mercedez car is of color  : "+obj.color+" and its latest : "+obj.computerized );




Output :


One more interesting thing about interface is that interfaces are not converted into javascript because it's a part of  Javascript.


Interfaces and Arrays

We have already covered array in our previous chapter. If you have not checked that, I recommend you to go through that first.  Interface is capable of defining both the kind of key and values.

Example

interface studentsList{

  [i:number]:string

}

var nameList:studentsList = ["Rajesh",255,"Anju"]
// the above code will generate error because 255 is not string

interface age{

  [j:string]:number

}

var agelist:age;

agelist["Kiran"] = 30   // Ok

agelist[5] = "Hetal"   // Error


Interfaces and Inheritance

Interface can be implemented by class and one interface can  An interface can be extended by other interfaces. In other words, an interface can inherit from other interface.

Example: Simple Interface Inheritance

interface Student {

 roll:number

}

interface WebDesignStudent extends Student {

 course:string

}

//implementation of interface thourgh create object

const designer: WebDesignStudent = {

  roll: 2,

  course: 'Web Design'

}

console.log("Roll:  "+designer.roll)
console.log("Course:  "+designer.course)

Output :


Example: Multiple Interface Inheritance

interface IParent1 {
  v1:number
}

interface IParent2 {
  v2:number
}

interface Child extends IParent1, IParent2 { }
var Iobj:Child = { v1:12, v2:23}
console.log("value 1: "+this.v1+" value 2: "+this.v2)

The object Iobj is of the type interface leaf. The interface leaf by the virtue of inheritance now has two attributes- v1 and v2 respectively. Hence, the object Iobj must now contain these attributes.

On compiling, it will generate following JavaScript code.

//Generated by typescript 1.8.10
var Iobj = { v1: 12, v2: 23 };
console.log("value 1: " + this.v1 + " value 2: " + this.v2);

The output of the above code is as follows −

value 1: 12   value 2: 23



Ad Image