You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Typescript编译JavaScript后类与extend代码差异问题咨询

这是完全正常的现象,并非系统问题

你看到的代码差异是TypeScript根据编译目标版本生成对应JS代码导致的:

  • 当TypeScript的编译目标(target)设为ES5或更低版本时,由于ES5本身没有原生class语法,TS会把class语法转译为基于构造函数+原型链的ES5兼容代码,也就是你现在看到的function实现形式。
  • 如果你希望编译后输出原生JS class语法,只需修改tsconfig.json中的target配置为ES6(或更高版本,如ES2015、ESNext)。

你的TypeScript代码

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

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

export {};

编译目标为ES5时的输出(你当前看到的结果)

"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));

修改编译目标为ES6后的输出示例

如果将tsconfig.json的target设为ES6,编译后的代码会更贴近TS的写法:

"use strict";
exports.__esModule = true;
class User4 {
    constructor(name) {
        this.name = name;
        this.city = "xyx";
        this.number = 123123;
    }
}
class additional extends User4 {
    method1() {
        console.log(this.number);
    }
}

内容的提问来源于stack exchange,提问作者BlackWatch021

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 15:00:49