Friday, October 24, 2025
HomeLanguagesJavascriptHow to check interface type in TypeScript ?

How to check interface type in TypeScript ?

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:

  • 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:
 

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS