A Class In TypeScript – Organized form of writing codes in JavaScript

Are you from an OOP background like JAVA or C#? If you are, then you probably have a pretty good idea about classes in these object-oriented programming languages then. A class is basically a blueprint of an object that defines all the methods and properties of the object. In most programming languages, the concept of a class is quite similar.

However, a class in TypeScript is quite unique and deserves a class of its own.


TypeScript is a typed superset of JavaScript that compiles into plain JavaScript. It is basically an organized form of writing codes in JavaScript. It combines the power of plain old JavaScript with the powerful concepts of object-oriented programming.



While TypeScript brings most of the concepts related to OOP like classes, interfaces, constructors and access modifiers, there are few interesting differences that TypeScript classes have from traditional OOP classes.

Single Constructor Per Class

Surprisingly, a TypeScript class can have only one constructor which means no constructor over-loading! So, you can not do something like below and have two constructors.

class StudentData
   private int stuID;
   private String stuName;
   private int stuAge;
       //Default constructor
       stuID = 100;
       stuName = "New Student";
       stuAge = 18;
   StudentData(int num1, String str, int num2)
       //Parameterized constructor
       stuID = num1;
       stuName = str;
       stuAge = num2;

Create Properties On The Fly

Using TypeScript, you can easily declare and create any properties from constructor without explicitly specifying them which you can not do in other OOP languages. For example, the following code would throw a “Null Exception” in C#, but it works perfectly fine in TypeScript.

class Greeter {
    constructor(public message: string) {
    greet() {
        return "Hello, " + this.message;

Interface From Class

In any OOP framework, you could never derive an interface from a concrete class. It is always the other way around i.e. you derive a class from an interface. However, in TypeScript, because classes create types, you can use them in the same places you would be able to use interfaces.

READ  10 Very Useful User Experience Tools For Every Designer

So you can do something like below!

class Point {
    x: number;
    y: number;

interface Point3d extends Point {
    z: number;

let point3d: Point3d = {x: 1, y: 2, z: 3};