Tuesday, June 9, 2026
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
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6896 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7018 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS