Interface In Typescript

Introduction

 
In this article you will learn about Interface in Typescript in detail. This article will help  beginners to understand. 
 
What is Interface?
  • It is like a blueprint of class, only method implementation is not possible in interface.
  • It contains properties, methods & events.
  • It is an interaction between two entities. 
  • Users have to give method definitions in implemented class of interfaces.
  • We can implement an interface by usin theg implements keyword in class.
For better understanding, consider a playMusic() function which is used in different players like Radio, Car Music Player, Touch Screen Music Player etc. Each one has  unique implementations.
 
Interface In Typescript
Syntax
 
Below is the syntax to define the interface:
  1. interface InterfaceName{    
  2.      // properties, methods & events
  3. }   
Example
 
Below example shows that we have IDepartment interface having one property & method. Class Department implements the interface & method is implemented in the class which returns any data type value. For the time being we are just returning a simple message from the function.
  1. interface IDepartment{  
  2.     deptId: number;  
  3.     getDetails(): any;  
  4. }  
  5. class Department implements IDepartment{  
  6.     deptId = 1000;  
  7.     getDetails():any{  
  8.         return "You are in getDetails function & deptId is : " + this.deptId;  
  9.     }  
  10. }  
  11. let objDept : Department = new Department();  
  12. console.log(objDept.getDetails());  
Output
 
You are in getDetails function & deptId is : 1000
 
 
Step 1
 
User cannot give definitions in the interface:
  1. interface IDepartment{  
  2.     getDetails(): any{  
  3.       // method implemetation not allow
  4.     }  
  5. }  
Step 2
 
Object creation of interface is not allowed:
  1. interface IDepartment{  
  2.     deptId: number;  
  3.     getDetails(): any{  
  4.     }  
  5. }  
  6. let obj: IDepartment = new IDepartment();  
Will get error - 'IDepartment' only refers to a type, but is being used as a value here.
 
Step 3
 
User can implement single interface in multiple classes:
  1. interface IDepartment{  
  2.     getDetails(): any;  
  3. }  
  4. class A implements IDepartment{  
  5.     getDetails(): any{  
  6.         console.log("You are in class A.")  
  7.     }  
  8. }  
  9. class B implements IDepartment{  
  10.     getDetails(): any{  
  11.         console.log("You are in class B.")  
  12.     }  
  13. }  
  14. let objA : A = new A();  
  15. objA.getDetails()  
  16. let objB : B = new B();  
  17. objB.getDetails()  
Output
 
 You are in class A.
 You are in class B. 
 
Step 4
 
User is not able to access/implement method directly using interface.methodName:
  1. interface IDepartment{  
  2.     getDetails(): any;  
  3.     getDetailsById(id: number): any;  
  4. }  
  5. class A implements IDepartment{  
  6.     getDetails(): any{  
  7.         console.log("Method getDetails called.");  
  8.     }  
  9.     IDepartment.getDetailsById(id:number):any {  
  10.         console.log("Method getDetailsById called.");  
  11.     }  
  12. }   
A) Function Types
 
We can use the interface as a type of function. Consider the below example, we have defined one property in the interface as name. While creating a function we are passing one parameter as object, which does not care about the order of parameter in that object. Only function is checking whether the parameter is of type object or not. In function we are just printing the name on the console.
 
Example
  1. interface IDepartment{  
  2.     name: string;  
  3. }  
  4. function getDetails(objIDept: IDepartment): any{  
  5.      console.log(objIDept.name)  
  6. }  
  7. let obj_1 : IDepartment = {name: "Computer Science"};  
  8. getDetails(obj_1);  
Output
 
Computer Science
 
Consider the below example, now for function we are passing the addition parameter in the object like below, and function prints that object in the console. So function is checking only for paramter as an object, nothing more than that.
 
Example
  1. interface IDepartment{  
  2. name: string;  
  3. }  
  4. function getDetails(objIDept: IDepartment): any{  
  5. console.log(objIDept)  
  6. }  
  7. let obj_1 : IDepartment = {name: "Computer Science"};  
  8. getDetails(obj_1);  
  9. let obj_2 = {name: "Maths", deptId : 2000};  
  10. getDetails(obj_2);  
Output
 
{name: "Computer Science"}
{name: "Maths", deptId: 2000}
 
B) Optional Properties
 
We can define the optional properties in the interface. The symbol '?' is used to define the optional property. So such kind of properties may be required. These are used when they are optional it may or may not be used or may not require a value.
 
Example
  1. interface IDepartment{  
  2. deptId: number;  
  3. name?: string;  
  4. deptType: string;  
  5. }  
  6. class Department implements IDepartment{  
  7.    deptId = 1000;  
  8.    deptType = "Store";  
  9. }  
  10. let obj: Department = new Department();  
  11. console.log(obj.deptId)  
  12. console.log(obj.deptType)  
Output
 
1000
store 
 
C) Readonly properties
 
We can define the readonly properties in the interface. The readonly keyword is used to define such kind of properties. The value is assigned when object gets created the first time, and not after that.
 
Example
  1. interface IDepartment{  
  2.    readonly deptId: number;  
  3.    readonly isActive: boolean;  
  4. }  
D) Indexable
 
We can define the Interface index into  colour[0] or colur['1']. It has a index signature used as a object type & is accessed by using index value. In the below example we have string array of color. Array can be accessible using index value, so the below color array has an index signature. Elements are stored in a continous manner.
 
Example
  1. interface ColourArray {  
  2.    [index: number]: string;  
  3. }  
  4.   
  5. let objArray: ColourArray;  
  6. objArray = ["red""orange""yellow"];  
  7. console.log(objArray[0]);  
  8. console.log(objArray[1]);  
  9. console.log(objArray[2]);  
Output
 
red
orange
yellow
 
We can define an object like index types as well as like below. Elements can be also accessed by using index position.
 
Example
  1. let colurs: object;  
  2. colurs = {1:"red", 2:"orange",3:"yellow"}  
  3. console.log(colurs['1']);  
  4. console.log(colurs['2']);  
  5. console.log(colurs['3']);  
Output
 
red
orange
yellow
 

Summary

 
In this article, you learned about Interfaces in Typescript.