Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

How to check interface type in TypeScript ?

  • Last Updated : 29 Sep, 2020

Typescript is a pure object-oriented programming language that consists of classes, interfaces, inheritance, etc. It is strict and it statically typed like Java. Interfaces are used to define contacts in typescript. In general, it defines the specifications of an entity. Below is an example of an interface or contract of a car.

interface Audi {
    length: number;
    width: number;
    wheelbase: number;
    price:number;
    numberOfAirBags:number;
    seatingCapacity: number;
    getTyrePressure: () => number;
}

Approach:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

  • Declare an interface with a name and its type as a string.
  • Now create a customized function to check the interface type.
  • This function returns a boolean value if the name attribute is present in the argument passed.
  • Now use an if statement to check the value returned by the function and can perform further operation regarding requirements.

Example 1:

Javascript






interface Student{
    name:string;
}
  
var geek:any = { 
    name: "Jairam" 
    };
  
function instanceOfStudent(data: any): data is Student {
    return 'name' in data;
}
  
if (instanceOfStudent(geek)) {
    document.write("Student Name is "+ geek.name);
}

Output:
 

Example 2:

Javascript




interface Bike{
    companyName:string;
    bikeNumber:any;
    modelNo:any;
}
  
var bike:any = { 
    companyName: "Engfield" 
    };
  
function createName(name:any){
   alert(name);
}
  
if(instanceOfBike(bike)) {
    createName(bike.companyName)
}
else{
    createName("No Name is registered with that company name")
}
  
function instanceOfBike(data: any): data is Bike {
    return 'companyName' in data;
}

Output:
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :