TypeScript Interface

An Interface is a structure which acts as a contract in our application. It defines the syntax for classes to follow, means a class which implements an interface is bound to implement all its members. We cannot instantiate the interface, but it can be referenced by the class object that implements it. The TypeScript compiler uses interface for type-checking (also known as "duck typing" or "structural subtyping") whether the object has a specific structure or not.

The interface contains only the declaration of the methods and fields, but not the implementation. We cannot use it to build anything. It is inherited by a class, and the class which implements interface defines all members of the interface.

When the Typescript compiler compiles it into JavaScript, then the interface will be disappeared from the JavaScript file. Thus, its purpose is to help in the development stage only.

Interface Declaration

We can declare an interface as below.

Syntax
interface interface_name {
          // variables' declaration
          // methods' declaration
}
  • An interface is a keyword which is used to declare a TypeScript Interface.
  • An interface_name is the name of the interface.
  • An interface body contains variables and methods declarations.
Example
snippet
interface OS {
    name: String;
    language: String;
}
let OperatingSystem = (type: OS): void => {
  console.log('Android ' + type.name + ' has ' + type.language + ' language.');
};
let Oreo = {name: 'O', language: 'Java'}
OperatingSystem(Oreo);

In the above example, we have created an interface OS with properties name and language of string type. Next, we have defined a function, with one argument, which is the type of interface OS.

Now, compile the TS file into the JS which looks like the below output.

snippet
let OperatingSystem = (type) => {
    console.log('Android ' + type.name + ' has ' + type.language + ' language.');
};
let Oreo = { name: 'O', language: 'Java' };
OperatingSystem(Oreo);
TypeScript Interface

Use of Interface

We can use the interface for the following things:

  • Validating the specific structure of properties
  • Objects passed as parameters
  • Objects returned from functions.

Interface Inheritance

We can inherit the interface from the other interfaces. In other words, Typescript allows an interface to be inherited from zero or more base types.

The base type can be a class or interface. We can use the "extends" keyword to implement inheritance among interfaces.

The following example helps us to understand the interface inheritance more clearly.

Syntax
child_interface extends parent interface{
}
Example #1
snippet
interface Person { 
   name:string
   age:number
}
interface Employee extends Person { 
   gender:string
   empCode:number
}
let empObject = {}; 
empObject.name = "Abhishek"
empObject.age = 25 
empObject.gender = "Male"
empObject.empCode = 43
console.log("Name: "+empObject.name);
console.log("Employee Code: "+empObject.empCode);
TypeScript Interface

Let us take the above example, which helps us to understand the multiple interface inheritance.

Example #2
snippet
interface Person { 
   name:string  
}
interface PersonDetail { 
    age:number
    gender:string
}
interface Employee extends Person, PersonDetail { 
    empCode:number
}
let empObject = {}; 
empObject.name = "Abhishek"
empObject.age = 25 
empObject.gender = "Male"
empObject.empCode = 43
console.log("Name: "+empObject.name);
console.log("Employee Code: "+empObject.empCode);
TypeScript Interface

Array Type Interface

We can also use interfaces to describe the array type. The following example helps us to understand the Array Type Interface.

Example
snippet
// Array which return string
interface nameArray {
    [index:number]:string
}
// use of the interface
let myNames: nameArray;
myNames = ['Virat', 'Rohit', 'Sachin'];

// Array which return number
interface ageArray {
    [index:number]:number
}
var myAges: ageArray;
myAges =[10, 18, 25];
console.log("My age is: " +myAges[1]);

In the above example, we have declared nameArray that returns string and ageArray that returns number. The type of index in the array is always number so that we can retrieve array elements with the use of its index position in the array.

TypeScript Interface

Interface in a class

TypeScript also allows us to use the interface in a class. A class implements the interface by using the implements keyword. We can understand it with the below example.

Example
snippet
// defining interface for class
interface Person {
    firstName: string;
    lastName: string;
    age: number;
    FullName();
    GetAge();
}
// implementing the interface
class Employee implements Person {
    firstName: string;
    lastName: string;
    age:number;
    FullName() {
        return this.firstName + ' ' + this.lastName;
    }
    GetAge() {
        return this.age;
    }
    constructor(firstN: string, lastN: string, getAge: number) {
        this.firstName = firstN;
        this.lastName = lastN;
        this.age = getAge;
    }
}
// using the class that implements interface
let myEmployee = new Employee('Abhishek', 'Mishra', 25);
let fullName = myEmployee.FullName();
let Age = myEmployee.GetAge();
console.log("Name of Person: " +fullName + '\nAge: ' + Age);

In the above example, we have declared Person interface with firstName, lastName as property and FullName and GetAge as method/function. The Employee class implements this interface by using the implements keyword. After implementing an interface, we must declare the properties and methods in the class. If we do not implement those properties and methods, it throws a compile-time error. We have also declared a constructor in the class. So when we instantiate the class, we need to pass the necessary parameters otherwise it throws an error at compile time.

TypeScript Interface

Difference between interface and inheritance

SN Interface Inheritance
1. An Interface is a structure which acts as a contract in our application. It defines the required functions, and the class is responsible for implementing it to meet that contract. Inheritance is object-oriented programming that allows similar objects to inherit the functionality and data from each other.
2. In an interface, we can only declare properties and methods. In inheritance, we can use a superclass to declare and defines variables and methods.
3. An interface type objects cannot declare any new methods or variables. In this, we can declare and define its own variables and methods of a subclass that inherits a superclass.
4. Interface enforces the variables and methods which have to be present in an object. A subclass extends the capability of a superclass to suit the "custom" needs.
5. Interface are classes that contain body-less structure (abstract or virtual functions). So, we have to derive the interface and then implement all of the functions in the subclass. Inheritance is the process where one subclass acquires the properties of its superclass.
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +