TypeScript Class Example

In this typescript example, we will see how to create a simple class in TypeScript with an example.

TypeScript Simple Class Example

Let's create a simple Employee class with the following members:
  • id
  • firstName
  • lastName
  • getFullName()
class Employee {
    id: number;
    firstName: string;
    lastName: string;

    constructor(id: number, firstName: string, lastName: string) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    getFullName() {
        return this.firstName + ' ' + this.lastName;
    }
}

// create Employee class object
let employee = new Employee(100, 'Ramesh', 'Fadatare');
console.log(employee);
console.log(employee.getFullName());
Output:
Employee { id: 100, firstName: 'Ramesh', lastName: 'Fadatare' }
Ramesh Fadatare
The TypeScript compiler will convert the above class to the following JavaScript code using closure:
"use strict";
exports.__esModule = true;
var Employee = /** @class */ (function () {
    function Employee(id, firstName, lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }
    Employee.prototype.getFullName = function () {
        return this.firstName + this.lastName;
    };
    return Employee;
}());
exports.Employee = Employee;
// create Employee class object
var employee = new Employee(100, 'Ramesh', 'Fadatare');
console.log(employee);
console.log(employee.getFullName());

Reference


Comments