Understanding Typescript Interfaces - Learn in 15 mins with examples

In this Blog Post, We are going to learn the Interfaces tutorials in typescript.

It is one of the concepts of Object Oriented Programming. Other concepts are Classes, polymorphism, Encapsulation and Abstract classes.

Interface Basic tutorial

typescript interfaces multiple Inheritance example

Interfaces in the typescript are same like in another programming language like in java. It doesn’t provide any implementation. It is a contract/rules for the object that implements the interfaces. Interfaces contain method header, member variables.when the interface is compiled to javascript, There is no code generated. that means, there is no interpretation of runtime code. It provides compile type checking for type-safety. The reason has not generated any code in javascript as there is no type checking. Interfaces allow developers to extend the code to extend to write own implementation.

Interface declaration

Interfaces can be created using the interface keyword and it contains member variables and method headers surrounded by braces.

interface interfacename{  
//member variables  
//methods without implementation  

Typescript Typesafety example

How type safety works in typescript?  Type checking is one of advantage over javascript.it is simple code for testing type checking.

Created interface which has member variable only name of type string. Created a class which implements this interface by providing a constructor with the public of interface variable

interface IEmployee {   
    name: string;  
class Employee implements IEmployee {   
    constructor(public name: string) {   
let validEmp: Employee = new Employee("frank"); // valid Object  
let invalidEmp: Employee = new Employee('kiran','abc'); // invalid Object  
let invalidEmp1: Employee = new Employee(1); // invalid Object  

validEmp is a valid class that implements interface initialization as parameter string is only passing.
invalidEmp is will throws compile time error- Expected 1 arguments, but got 2. constructor accepts only one string, but we are passing two strings
invalidEmp1 - throws compile time error - Argument of type ‘1’ is not assignable to a parameter of type ‘string’. the reason is creating an object with numeric whereas it accepts values of type string only. The advantages for developers with type safety is avoiding issues with types at runtime.
Please see below screenshot how code generates in typescript.

typescript interface example with tutorials

Interface different member variables declaration example

In this below section, we will see various use cases of declaring different variable types.

Interface Optional Types example

Sometimes, when the interface is passing to function, the caller of the function will not send all the required parameters. Optional member variables are declared with a question mark(?) at end of the variable. IShape interface has two optional parameters and another function has interface parameter. Calling the function with interface contains works either with zero parameters, one parameter, two parameters.

interface IShape {   
    length?: number;  
    width?: number;  
function createShape(shape: IShape): any{  
let shape = createShape({ length: 10 }) //valid  
let shape1 = createShape({}) //valid  
let shape2 = createShape({ length: 10,width:20 }) //valid  

Interface Readonly Types example

 This is one more way of declaring an interface definition to give more flexibility to developers. Readonly keyword is used with a member variable and declared before the variable. the member variable is initialized during object creation. Once values are assigned, variables will not be modified at any cost Once values are assigned, if the value is assigned to legs property, It compiles, whereas assigning to ears will not compile as this is readonly property

interface Animal {   
     readonly ears: number;  
    legs: number;  
let animal: Animal = { ears: 2, legs: 4 }  
animal.ears = 1;// this will not compiles  
animal.legs = 4; // this compiles fine  

Function interface Example 

Functions types can be declared with interfaces. This is like Function header + arguments+ type Function calling should have the same number of arguments with the name might be different, the type should be same and return type should be the same Declaration and calling the function

interface Vehicle {  
    (name: string,  
    wheels:number): string;  
let car: Vehicle;  
car = function(n: string, w: number) {  
    return n;  

You can omit function types string, number as typescript can type infer based on the values passed.

Index types signature Example

We can also declare interface parameters with index types. when do you use this ?. simple if interface contains a lot of member variables of the same type, we will use this. This is kind of array declaration in interfaces.

numberArray has index signature, with numeric index starts from zero. Index signature only applicable to string and number datatypes

interface numberArray {  
    [index: number]: number;  
let arr: numberArray;  
arr = [11,5,8];  
console.log(arr[0]); // returns 11  

Interfaces inheritance examples

  Inheritance is one of the important concepts in object oriented programming. It allows to extends the common things and enables reuse mechanism. This provides Inheritance using implements and extends keywords.

Using extend example

- inheritance example This is single inheritance as superclass only extended by one class

interface Animal {   
interface Lion extends Animal {   
var lion = {};   
lion.legs = 4   
lion.eat = "nonveg"   
console.log('Number of legs='+ lion.legs+' Eat type= '+lion.eat);  

Javascript generated code

var lion = {};  
lion.legs = 4;  
lion.eat = "nonveg";  
console.log('Number of legs=' + lion.legs + ' Eat type= ' + lion.eat);  

the output of the above code is

Number of legs=4 Eat type= nonveg  

Multiple inheritances are directly not possible, But you can achieve using implements or indirect inheritance as like below

Using implements interface example

with implements keyword, you can implement multiple interfaces Please see below example. In this example created two interfaces. created class by implementing two interfaces. You can achieve multiple inheritances like this

interface ISuper1{  
interface ISuper2{  
class Child implements ISuper1, ISuper2 {  
        console.log('Method 1');  
        console.log('Method 2');  
var child = new Child();  

Similar Posts