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.
Syntax
Below is the syntax to define the interface:
- interface InterfaceName{
- & events
- }
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.
- interface IDepartment{
- deptId: number;
- getDetails(): any;
- }
- class Department implements IDepartment{
- deptId = 1000;
- getDetails():any{
- return "You are in getDetails function & deptId is : " + this.deptId;
- }
- }
- let objDept : Department = new Department();
- console.log(objDept.getDetails());
Output
You are in getDetails function & deptId is : 1000
Step 1
User cannot give definitions in the interface:
- interface IDepartment{
- getDetails(): any{
- // method implemetation not allow
- }
- }
Step 2
Object creation of interface is not allowed:
- interface IDepartment{
- deptId: number;
- getDetails(): any{
- }
- }
- 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:
- interface IDepartment{
- getDetails(): any;
- }
- class A implements IDepartment{
- getDetails(): any{
- console.log("You are in class A.")
- }
- }
- class B implements IDepartment{
- getDetails(): any{
- console.log("You are in class B.")
- }
- }
- let objA : A = new A();
- objA.getDetails()
- let objB : B = new B();
- 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:
- interface IDepartment{
- getDetails(): any;
- getDetailsById(id: number): any;
- }
- class A implements IDepartment{
- getDetails(): any{
- console.log("Method getDetails called.");
- }
- IDepartment.getDetailsById(id:number):any {
- console.log("Method getDetailsById called.");
- }
- }
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
- interface IDepartment{
- name: string;
- }
- function getDetails(objIDept: IDepartment): any{
- console.log(objIDept.name)
- }
- let obj_1 : IDepartment = {name: "Computer Science"};
- 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
- interface IDepartment{
- name: string;
- }
- function getDetails(objIDept: IDepartment): any{
- console.log(objIDept)
- }
- let obj_1 : IDepartment = {name: "Computer Science"};
- getDetails(obj_1);
- let obj_2 = {name: "Maths", deptId : 2000};
- 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
- interface IDepartment{
- deptId: number;
- name?: string;
- deptType: string;
- }
- class Department implements IDepartment{
- deptId = 1000;
- deptType = "Store";
- }
- let obj: Department = new Department();
- console.log(obj.deptId)
- 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
- interface IDepartment{
- readonly deptId: number;
- readonly isActive: boolean;
- }
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
- interface ColourArray {
- [index: number]: string;
- }
-
- let objArray: ColourArray;
- objArray = ["red", "orange", "yellow"];
- console.log(objArray[0]);
- console.log(objArray[1]);
- 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
- let colurs: object;
- colurs = {1:"red", 2:"orange",3:"yellow"}
- console.log(colurs['1']);
- console.log(colurs['2']);
- console.log(colurs['3']);
Output
red
orange
yellow
Summary
In this article, you learned about Interfaces in Typescript.