TypeScript Interface Tutorial with Examples

An Interface is a structure that acts as a contract in our application. It defines the syntax for classes to follow, which means a class that 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. 
Learn typescript at TypeScript Tutorial with Examples.
The TypeScript compiler does not convert the interface to JavaScript. It uses interface for type checking. This is also known as "duck typing" or "structural subtyping".

Table of Contents

  1. Simple Interface Example
  2. Interface Optional Properties Example
  3. Interface Readonly properties Example
  4. Extending Interfaces Example
  5. Implementing an Interface Example
  6. Interface for Array Type Example

1. Simple Interface Example

export interface Employee{
    firstName: string;
    lastName: string;
    fullName(): string;
}

let employee: Employee = {
    firstName : "ramesh",
    lastName: "fadatare",
    fullName(): string{
        return this.firstName + " " + this.lastName;
    }
}

console.log(employee.firstName);
console.log(employee.lastName);
console.log(employee.fullName());
Output:
C:\typescript-tutorial> tsc interfaces.ts
C:\typescript-tutorial> node interfaces.js
ramesh
fadatare
ramesh fadatare
The above typescript code is compiled into below plain JavaScript code:
"use strict";
exports.__esModule = true;
var employee = {
    firstName: "ramesh",
    lastName: "fadatare",
    fullName: function () {
        return this.firstName + " " + this.lastName;
    }
};
console.log(employee.firstName);
console.log(employee.lastName);
console.log(employee.fullName());
Note that the TypeScript compiler does not convert the interface to JavaScript.

2. Interface Optional Properties Example

Not all properties of an interface may be required. Interfaces with optional properties are written similar to other interfaces, with each optional property denoted by a ? at the end of the property name in the declaration. 
Here’s an example of this pattern:
interface SquareConfig {
    color?: string;
    width?: number;
}

function createSquare(config: SquareConfig): {color: string; area: number} {
    let newSquare = {color: "white", area: 100};
    if (config.color) {
        newSquare.color = config.color;
    }
    if (config.width) {
        newSquare.area = config.width * config.width;
    }
    return newSquare;
}

let mySquare = createSquare({color: "black"});
console.log(mySquare);
Output:
{ color: 'black', area: 100 }
The advantage of optional properties is that you can describe these possibly available properties while still also preventing the use of properties that are not part of the interface.

3. Interface Readonly properties Example

TypeScript provides a way to mark a property as readonly. This means that once a property is assigned a value, it cannot be changed!:
interface Point {
    readonly x: number;
    readonly y: number;
}
You can construct a Point by assigning an object literal. After the assignment, x and y can’t be changed.
let p1: Point = { x: 10, y: 20 };
p1.x = 5; // error!

4. Extending Interfaces Example

Interfaces can extend one or more interfaces. This makes writing interfaces flexible and reusable.
interface IAddress {
    address: string;
} 

interface IPerson extends IAddress{
    firstName: string;
    lastName: string;
}

interface IEmployee extends IPerson {
    employeeCode: number;
}

let employeeObj: IEmployee = {
    firstName: "ramesh",
    lastName: "fadatare",
    address: "pune",
    employeeCode: 100
}

console.log(employeeObj);
Output:
{ color: 'black', area: 100 }
{ firstName: 'ramesh',
  lastName: 'fadatare',
  address: 'pune',
  employeeCode: 100 }

5. Implementing an Interface Example

Similar to languages like Java and C#, interfaces in TypeScript can be implemented with a Class.
interface Employee {

    name: string;
    paymentPerHour: number;
    workingHours: number;
    calculateSalary(): number;
}

class Contractor implements Employee {
    name: string;
    paymentPerHour: number;
    workingHours: number;
    constructor(name: string, paymentPerHour: number, workingHours: number) {
        this.name = name;
        this.paymentPerHour = paymentPerHour;
        this.workingHours = workingHours;
    }

    calculateSalary(): number {
        return this.paymentPerHour * this.workingHours;
    }
}

class FullTimeEmployee implements Employee {
    name: string;
    paymentPerHour: number;
    workingHours: number;

    constructor(name: string, paymentPerHour: number) {
        this.name = name;
        this.paymentPerHour = paymentPerHour;
    }

    calculateSalary(): number {
        return this.paymentPerHour * 8;
    }
}

let contractor: Employee;
let fullTimeEmployee: Employee;
contractor = new Contractor('Ramesh contractor', 10, 5);
fullTimeEmployee = new FullTimeEmployee('Ramesh full time employee', 8);

console.log(contractor.calculateSalary());
console.log(fullTimeEmployee.calculateSalary());
Output:
C:\typescript-tutorial> tsc interfaces.ts
C:\typescript-tutorial> node interfaces.js
50
64

6. Interface for Array Type Example

An interface can also define the type of an array where you can define the type of index as well as values
interface NumList {
    [index:number]:number
}

let numArr: NumList = [1, 2, 3];
numArr[0];
numArr[1];
console.log(numArr);


// Array which return string
interface ProLangArray {
    [index:number]:string
}

// use of the interface  
let progLangArray : ProLangArray = ['C', 'C++', 'Java', 'Python'];
console.log(progLangArray);
Output:
[ 1, 2, 3 ]
[ 'C', 'C++', 'Java', 'Python' ]
Learn typescript at TypeScript Tutorial with Examples.

Comments