TypeScript Interface Example

This post shows how to use interface in TypeScript with an example.

In TypeScript, interfaces allow us to create contracts other classes/ objects have to implement. We can use them to define custom types without creating classes.

Read the complete tutorial at https://www.javaguides.net/2019/10/typescript-interface-tutorial-with-examples.html.

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.

Reference


Comments