Explaining Interfaces in TypeScript with Examples

In this post on Explaining Interfaces in TypeScript with Examples, I will demonstrate how to create and use an interface in TypeScript.

Interfaces in TypeScript

Similar to the interfaces in other programming languages, TypeScript also has interfaces and they also serve the same purpose of providing a specification before the implementation. Essentially, interfaces allow us to have a contract between the user and the developer and they make it easy for the users to find out whether the resulting software has all the desired functionality.

Indeed, interfaces also provide lots of convenience to the developers, if they are going to develop a complex system. Moreover, testing a software product is also easy when interfaces are created beforehand.

Basically, an interface describes what functionality should be included in the end product without explicitly providing the details of implementation. Moreover, interfaces also let us define a common signature of methods that different classes implement.

Defining and Implementing Interfaces

We define an interface using the interface keyword. Further, in TypeScript, we not only define interfaces for implementation by a class, but a function, an array, or a type can also be implemented using the interface.

In all such cases, the interface essentially creates a contract that the implementing entity must follow. In other words, the implementing entities should have exactly those properties and methods declared in the interface.

Interface for the Class Type

To begin with, the examples of interfaces, let us create an interface with name I1 and two classes with name sum and multiply that is implementing this interface. As can be seen, the interface I1 has two properties a and b. Also, it declares a method with the name find(). Furthermore, the method find() is optional and classes implementing this interface need not define this method.

Now that, the definition of classes and interface is complete, we create the objects of three classes and display them. finally, we call the method find() using the objects of class sum and class multiply respectively.

interface I1
{
	a: number;
	b: number;
	find?:Function;
}
class sum implements I1
{
	constructor(public a, public b){}
        public find()
        {
		return this.a+this.b;
        }
}
class multiply implements I1
{
	constructor(public a, public b){}
        public find()
        {
		return this.a*this.b;
        }
}
class MyClass implements I1
{
	constructor(public a, public b){}
}
let ob1=new sum(34, 12);
let ob2=new multiply(340, 8);
let ob3=new MyClass(20, 120);

//Display three objects
console.log("Object of class sum: ");
console.log(ob1);
console.log("Object of class multiply: ");
console.log(ob2);
console.log("Object of class MyClass: ");
console.log(ob3);

console.log("Display sum: ");
console.log("Sum: "+ob1.find());
console.log("Display Multiplication: ");
console.log("Multiply: "+ob2.find());

Output

Classes Implementing the Interface
Classes Implementing the Interface

Interface that a Function Implements

Besides classes, we can also use interfaces to declare the types used by a function. In other words, an interface can declare the signature of a method.

As an illustration, the following example defines two interfaces with the name area and interest respectively. Further, the two functions with names RectangleArea() and TriangleArea() are defined with signature exactly matching the one which the interface area specifies. Similarly, the two functions namely SimpleInterest() and CompoundInterest() have the signatures matching with the interface called interest.

Additionally, we create four variables v1, v2, v3, and v4 of the specific interface type and point them to a particular function. Finally, we call the functions using these variables.

interface area{
	(x: number, y: number):number
};

interface interest{
	(i:number, j:number, k:number):number
}

function RectangleArea(i:number, j:number):number{
	return i*j;
}

function TriangleArea(i:number, j:number):number{
	return 0.5*i*j;
}

function SimpleInterest(a:number, b:number, c:number): number{
  return (a*b*c)/100.0;
}

function CompoundInterest(a:number, b:number, c:number): number{
	let amount=a*Math.pow((1+b/100.0), c);
        return Math.round(amount-a);
}

let v1: area = RectangleArea;
console.log("Area of Rectangle = "+v1(20, 15));

let v2: area = TriangleArea;
console.log("Area of Triangle = "+v2(20, 15));

let v3: interest = SimpleInterest;
console.log("Simple Interest = "+v3(20000, 4.5, 3));

let v4: interest = CompoundInterest;
console.log("Compound Interest = "+v4(20000, 4.5, 3));

Output

Function Implementing Interface in TypeScript
Function Implementing Interface in TypeScript

Array Types Implementing Interfaces

Analogous to the above illustrations, we can also use interfaces to define the arrays. In other words, an interface can specify the type of an array element as well as the type of the array index. As evident from the following example, the interface general_array specifies an array of numeric elements with a numeric type index. However, the interface some_array specifies an array of numeric type elements with string type index.

Furthermore, the arrays arr1, and arr2 implement the interface general_array, whereas the array arr3 implements the interface some_array. Finally, we assign values to these arrays and display them as shown in the output.

interface general_array{
	[i:number]:number;
}

let arr1:general_array=Array(10);
let arr2:general_array=[1,2,3,4,5];

for(let i=0;i<10;i++)
{
	arr1[i]=i;
}

let str="";
for(let i=0;i<10;i++)
{
	str+=arr1[i]+" ";
}
console.log("Displaying elements of arr1: ");
console.log(str);
str="";
for(let i=0;i<5;i++)
{
	str+=arr2[i]+" ";
}
console.log("Displaying elements of arr2: ");
console.log(str);

//interface for arrays with index of type string

interface some_array{
	[i:string]:number;
}
let arr3 = {} as some_array;
arr3["ab"]=10;
arr3["bc"]=20;
arr3["cd"]=30;

let str1="";
let str2="";
for(var x in arr3)
{
	str1+=x+" ";
	str2+=arr3[x]+" ";
}

console.log("Displaying index values of arr3...");
console.log(str1);
console.log("Displaying array elements of arr3...");
console.log(str2);

Output

Arrays Implementing the Interface
Arrays Implementing the Interface

Implementing Types with Interfaces

In fact, an interface can also specify a type that we can use to create a class. In other words, we can have an interface which have only properties. Later, we can create variables having type as specified by the interface.

As an illustration, consider the following example which creates an interface Seller with some properties. Moreover, the property location is optional and for a variable implementing this interface, it is not mandatory to have this optional property. As can be seen, the variable seller1 and seller2 implement the interface Seller. However, the variable seller2 doesn’t define the property location.

interface Seller{
 seller_id: number;
 company_id: number;
 gstin: string;
 location?: string;
}
let seller1:Seller = {seller_id:1, company_id:11, gstin:"abc", location:"Delhi"};

let seller2:Seller = {seller_id:2, company_id:12, gstin:"aa1"};

console.log("Seller 1: ");
console.log(seller1);
console.log("Seller 2: ");
console.log(seller2);

Output

Implementing Types Through Interfaces
Implementing Types Through Interfaces

Summary

In this article on Explaining Interfaces in TypeScript with Examples, I have explained how to define an interface and implement it using various ways. As shown above, we use interfaces to create a class, functions, types, and arrays.


Related Topics

Introduction to Programming in TypeScript

Creating Classes in TypeScript

Working with Arrays in TypeScript

Significance of Tuples in TypeScript

Leave a Comment

Your email address will not be published. Required fields are marked *