TypeScript Constructor Example

The constructor is a special type of method which is called when creating an object. In TypeScript, the constructor method is always defined with the name "constructor".

Example: Constructor

class Employee {
    id: number;
    firstName: string;
    lastName: string;

    constructor(id: number, firstName: string, lastName: string) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }
}
In the above example, the Employee class includes a constructor with the parameters idfirstName, and lastName. In the constructor, members of the class can be accessed using this keyword e.g. this.firstName or this.lastName.
It is not necessary for a class to have a constructor.
class Employee{
    id: number;
    firstName: string;
    lastName: string;

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

// create Employee class object
let employee = new Employee();
employee.id = 100;
employee.firstName = 'Ramesh';
employee.lastName = 'Fadatare';

console.log(employee);
console.log(employee.getFullName());
Output:
Employee { id: 100, firstName: 'Ramesh', lastName: 'Fadatare' }
Ramesh Fadatare

Read more in the below tutorial





Comments