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

TypeScript继承代码报错:Uncaught ReferenceError: _super is not defined

解决TypeScript中_super is not defined的报错问题

嘿,这个问题我太熟悉了!你碰到的VM490:11 Uncaught ReferenceError: _super is not defined错误,本质原因很简单:你直接在浏览器环境里运行了未编译的TypeScript代码。

浏览器本身只认识原生JavaScript,而TypeScript的extends类继承语法,在被编译为JS时会自动生成依赖_super变量的逻辑(用来指代父类)。但如果你跳过编译步骤直接把TS代码丢给浏览器,它完全看不懂这些TS特有的语法转换,自然会抛出_super未定义的引用错误。

两种靠谱的解决方法

1. 本地编译TypeScript为JavaScript后再运行

这是生产环境和日常开发的标准做法:

  • 先全局安装TypeScript(如果还没装):
    npm install -g typescript
    
  • 把你的TS代码保存成一个.ts文件,比如animal.ts
  • 执行编译命令,生成对应的JS文件:
    tsc animal.ts
    
  • 现在你会得到一个animal.js文件,把它引入浏览器或者在Node环境里运行,就不会报错了。

2. 临时调试:用在线TypeScript环境直接运行

如果你只是想快速测试代码,不想折腾本地编译,可以用TypeScript官方的在线运行环境(实时编译并执行TS代码),写好代码就能直接看到结果,不用管编译的事儿。

附:编译后的JavaScript示例

你写的TS代码编译后会变成类似这样的JS(这里的_super就是编译生成的父类指代变量):

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 __());
    };
})();
var Animal = /** @class */ (function () {
    function Animal(name, speed) {
        this.speed = speed;
        this.name = name;
    }
    return Animal;
}());
var Rabbit = /** @class */ (function (_super) {
    __extends(Rabbit, _super);
    function Rabbit(name, speed) {
        return _super.call(this, name, speed) || this;
    }
    return Rabbit;
}(Animal));
(function () {
    var rabbit = new Rabbit("White Rabbit", 10);
    console.log(rabbit);
})();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:45:40