Home > Software engineering >  TypeScript classes into Javascript
TypeScript classes into Javascript

Time:02-05

I am learning about classes in Typescript and extend. Once I compiled .ts file and looked into .js. The code for class and extend in js is quite different. In .js class is made with function not with class.

My TS code

 class User4 {
      private city: string = "xyx";
      protected number: number = 123123;
      constructor(public name: string) {}
    }

    class additional extends User4 {
      method1() {
        console.log(this.number);
      }
    }

    export {};

While the code in **.js ** is

"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value "   String(b)   " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
exports.__esModule = true;
var User4 = /** @class */ (function () {
    function User4(name) {
        this.name = name;
        this.city = "xyx";
        this.number = 123123;
    }
    return User4;
}());
var additional = /** @class */ (function (_super) {
    __extends(additional, _super);
    function additional() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    additional.prototype.method1 = function () {
        console.log(this.number);
    };
    return additional;
}(User4));

I am wondering, if there is any issue with my system or its something else because the code in .js file is really crazy

CodePudding user response:

JavaScript doesn't have real classes. Classes in JS are syntax sugar, take a look at this article: How Classes work in JavaScript

You're getting this "crazy" code, because the transpiler is by default set to handle old versions of JavaScript, before class was even added as part of the language.

  • Related