TypeScript Class, Constructor and Object Creation

TypeScript follows ECMAScript 2015, also known as ECMAScript 6 standard that allows JavaScript developers to build their applications using object-oriented class-based approach. With object oriented you can create classes where class can inherit functionality and objects are built from these classes.

In TypeScript developers are free to use these object oriented technique to write JavaScript code and can compile them into JavaScript that support all the major browsers and platforms. Writing class in TypeScript is pretty simple if you are C# or Java developers.

TypeScript Class and Constructor Example

class Customer{
    fname: string;
    lname: string;
    address: string;
    phone: string;
    constructor(fname: string, lname: string, address: string, phone: string) {
        this.fname = fname;
        this.lname = lname;
	 this.address = address;
	 this.phone = phone;
    printCustomer() {
        return "Hello, " + this.fname + "  " + this.lname;
var cust = new Customer("Jimi", "Scott", "12-13/A12", "984563332");
Try it Yourself

In the above example, a new class Customer has created. This class created with four properties, one constructor and method called printCustomer. In the class, notice that member are using with this keyword which denoted that it's member access. In the code example class instance are created using new keyword by passing parameters value. This will run class constructor and assign passed value to the class members. Next, class object is used to call member function of the class called printCustomer. This member function will display customer first name and last name prefix with "Hello".