3.9 Class Expressions vs. Class Declarations

ES6 supports two styles of creating classes: class declarations and class expressions. The TypeScript the 1.6 release introduces support for class expressions.

Getting Ready

All you need to be able to use class expressions is an installation of TypeScript 2.0 or higher.

How to do it…

The following code snippet showcases how to use a class expression:

const Recto = class {
  area: number;

  constructor(public length: number, public width: number) {
    this.area = this.length * this.width;
  }
}

The equivalent using a class declaration would be:

class Rect {
  area: number;

  constructor(public length: number, public width: number) {
    this.area = this.length * this.width;
  }
}

How it works…

As we can observe in the two preceding code snippets, the main differences between the two styles are:

  • Class declarations can be unnamed.
  • Class declarations require the definition of a variable to store a reference to the declared class when the class is unnamed.

By observing the generated JavaScript code for the class expression:

var Rect = (function () {
    function class_1(length, width) {
        this.length = length;
        this.width = width;
        this.area = this.length * this.width;
    }
    return class_1;
})();

And the class declaration:

var Rect = (function () {
    function Rect(length, width) {
        this.length = length;
        this.width = width;
        this.area = this.length * this.width;
    }
    return Rect;
})();

We can also notice that class expressions use an internal name (class_1), which is not available outside the scope of the class declaration.

Source Code

Class Expressions vs. Class Declarations


Shiv Kushwaha

Author/Programmer