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: