Table of contents
1.
Introduction 
2.
The syntax for declaring interfaces in typescript
3.
Usage
4.
What are extending interfaces?
5.
Inheritance of Interfaces using the implements keyword
6.
Different properties in interfaces
7.
Frequently Asked Questions
8.
Key Takeaways
Last Updated: Mar 27, 2024

Interfaces in typescript

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction 

Typescript is a programming language that Microsoft developed. It is like a superset of the more commonly used Javascript. For developing large-scale applications, Typescript is designed Since it is a superset of Javascript, existing Javascript programs are also valid in Typescript. 

In Typescript, the interface is a set of guidelines for the syntax of an entity. The entity must adhere to the interface to be valid.

For example,

var object = { 
item:"Pencil", 
price:10,
qty:10,
sayTotal: ()=>{ return total} 
};

For the above variable, the interface would look like this,

{ 
item:string, 
price:number, 
qty:number,
sayTotal()=>number 
}

The syntax for declaring interfaces in typescript

The syntax for declaring an interface looks something like this,

interface product { 
   name:string, 
   price:number,
   qty:number, 
   sayTotal: ()=>number 
} 


var item_1:product = { 
   name:"Pencil",
   price:10,
   qty:10, 
   sayTotal: ():number =>{return item_1.price*item_1.qty} 
}
console.log(item_1.name);
console.log(item_1.price); 
console.log(item_1.qty);
console.log(item_1.sayTotal()); 

Output:

We declared an interface in the above example named product, and the variable item_1 is of type product.

Usage

Interfaces can be used for multiple purposes. Here we will see some of the scenarios in which interfaces in Typescript are helpful,

  • Interfaces can be used to validate a specific structure of an entity.
  • Interfaces can also be used to validate the objects passed as a parameter to a function.
  • Interfaces can also validate objects returned from a particular function.

What are extending interfaces?

Similar to the classes in Typescript, the interfaces can also be inherited in other interfaces or classes using the extends keyword. Although contrary to class inheritance, interface inheritance provides the option of Multiple Inheritance. That is, a class or interface can inherit multiple interfaces. Let us look at an example to understand extending interfaces in typescript better,

interface Code {   
   prodCode:number    
}  
interface ProdDetail {   
    name:string  
    price:number  
}  
interface Quantity extends Code, ProdDetail {   
    qty:number  
}  
let obj = <Quantity>{};   
obj.name = "Pencil"  
obj.price = 10   
obj.qty = 5  
obj.prodCode = 20  
console.log("Product Name: "+obj.name);  
console.log("Product Code: "+obj.prodCode);
console.log("Total Amount: "+(obj.price*obj.qty));   

Output:

In this example, we have inherited the Code and ProdDetail interfaces in the Quantity interface.

Inheritance of Interfaces using the implements keyword

Interfaces can also be inherited in a class using the implements keyword. 

For example,

interface Product {  
    name: string;  
    price: number;  
    qty: number;  
    GetAmount();  
}  
// implementing the interface  
class Item implements Product {  
    name: string;  
    price: number;  
    qty: number;  
    GetAmount(){
        return this.price*this.qty;
    }    
    constructor(Name: string, Price: number, quantity: number) {  
        this.name = Name;  
        this.price = Price;  
        this.qty = quantity;  
    }  
}  
// using the class that implements interface  
let myitem = new Item('Notebook', 100, 10);  
let Amount = myitem.GetAmount();  
console.log("Name of Product: " +myitem.name + '\nAmount: ' + Amount);

Output:

We have inherited the Product interface in the Item class in the above example, and then we created an object of the Item class and used it to call the constructor and the functions.

Different properties in interfaces

  • Optional properties

The interface can include optional properties, and for declaring optional properties, we use a question mark (?) at the end of the property name during declaration.

Example:

interface Girl {
    firstName: string;
    middleName?: string;
    lastName: string;
}

This example contains two properties and one optional property.

Now we will see how to use the girl interface in getFullName() function.

function getFullName(girl: Girl) {
    if (girl.middleName) {
        return `${girl.firstName} ${girl.middleName} ${girl.lastName}`;
    }
    return `${girl.firstName} ${girl.lastName}`;
}
  • Read-only properties

We can use the keyword readonly before the property's name; if we want, the properties should be modifiable only when the object is first created.

interface Girl {
    readonly ssn: string;
    firstName: string;
    lastName: string;    
}


let girl: Girl;
girl = {
    ssn: '171-67-0926',
    firstName: 'mansi',
    lastName: 'dubey'
}

Here we can not change the value of the ‘ssn’ property. Let's see what output it will give if we do so.

girl.ssn= '171-67-6534';

Output:

Frequently Asked Questions

1.What is the difference between interfaces and inheritance?

Interfaces allow us to declare property and methods only, and interface-type objects can not declare new methods or variables. 

But inheritance allows us to declare variables and methods using superclass. Furthermore, a subclass inheriting a class can declare its variables and methods.

 

2.What are array-type interfaces in typescript?

For defining the array type, we can also use interfaces.

For example -

// Array which return string  
interface nameArray {  
    [index:number]:string  
}  
// use of the interface  
let myNames: nameArray;  
myNames = ['Virat', 'Dhoni', 'Rahul'];  
  
// Array which return number  
interface ageArray {  
    [index:number]:number  
}  
var myAges: ageArray;  
myAges =[35, 20, 25];  
console.log("My age is: " +myAges[1]);  

Output-

Here we have a declared array with the name myName, which returns a string, and we have another array myAges that produce numbers so that using the array element's index position, we can retrieve them.

Key Takeaways

In this blog, we learned about interfaces in Typescript and how it is used with the help of various examples. Don't come to a halt here. Check out our Typescript vs Javascript: Learn the difference | Coding Ninjas Blog. Can you also check out the TypeScript Interview Questions | Part 1 | Coding Ninjas Blog blog? Check out more blogs here. More Blogs.

Happy Learning!

Live masterclass