Jack_of_All_Trades
Jack_of_All_Trades

Reputation: 11498

Typescript and equivalent js code

I am starting with typescript and I came across John Papa's tutorial. He had the following:

// TypeScript
class Car {  
    // Property (public by default)
    engine: string;

    // Constructor 
    // (accepts a value so you can initialize engine)
    constructor(engine: string) {
        this.engine = engine;
    }
}

the equivalent js code:

// JavaScript
var Car = (function () {  
    function Car(engine) {
        this.engine = engine;
    }
    return Car;
})();

It got me confused. Shouldn't it be:

    function Car(engine) {
        this.engine = engine;
    }

Am I missing something here?

Upvotes: 1

Views: 1055

Answers (1)

Remo H. Jansen
Remo H. Jansen

Reputation: 25029

You are right but there is a reason for the TypeScript code to look like that...

It becomes more obvious once you add some methods to your class:

class Car {  
    engine: Engine;
    constructor(engine: Engine) {
        this.engine = engine;
    }
    drive() { 
        this.engine.start();
    }
}

The output JS look as follows:

var Car = (function () {
    function Car(engine) {
        this.engine = engine;
    }
    Car.prototype.drive = function () {
        this.engine.start();
    };
    return Car;
}());

As you can see TS uses a IIFE to wrap the entire class declaration.

It is a nice way to keep everything together.

Another example using decorators:

@decorate
class Car {  
    engine: Engine;
    constructor(engine: Engine) {
        this.engine = engine;
    }
    drive() { 
        this.engine.start();
    }
}

And the output JS:

var Car = (function () {
    function Car(engine) {
        this.engine = engine;
    }
    Car.prototype.drive = function () {
        this.engine.start();
    };
    Car = __decorate([
        decorate
    ], Car);
    return Car;
}());

Upvotes: 2

Related Questions