打字稿错误"类不是构造函数"

Bar*_*ula 7 typescript ecmascript-6

我在ES6目标环境中运行以下打字稿代码,它说"汽车不是构造函数"

我已经按照链接尝试将目标环境更改为ES5.它工作正常.有人可以说明为什么它不适用于目标ES6.

这是我的TypeScript代码:

export class Cars {
    constructor(public len: number,public wid: number) { }
}

export function getSize(): Cars {
    return new Cars(20, 30);
};
Run Code Online (Sandbox Code Playgroud)

函数getSize中的错误是"汽车不是构造函数".

顺便说一下,我试图用Systemjs加载所有文件.

顺便说一句,我在浏览器中收到错误........而不是在编译时......

这是上面打字稿的编译代码....

System.register([], function(exports_1, context_1) {
    "use strict";
    var __moduleName = context_1 && context_1.id;
    var Cars;
    function getSize() {
        return new Cars(20, 30);
    }
    exports_1("getSize", getSize);
    return {
        setters:[],
        execute: function() {
            class Cars {
                constructor(len, wid) {
                    this.len = len;
                    this.wid = wid;
                }
            }
            ;
            exports_1("Cars", Cars);
        }
    }
});
//# sourceMappingURL=Cars.js.map
Run Code Online (Sandbox Code Playgroud)

Jam*_*oms 5

确保您没有.js.ts文件在同一目录中。这有时可能是由您的 IDE 引起的。

  • 是的,刚刚更改了 tsconfig 中的 outDir。工作了,谢谢 (2认同)

Arn*_*ion 4

(从您打开的 GH 问题中复制我的帖子。

这是 TS 1.8.10 中的一个错误,并在 master 中修复。

tsc -t es6 ./foo.ts -m system

1.8.10 中给出:

System.register([], function(exports_1, context_1) {
    "use strict";
    var __moduleName = context_1 && context_1.id;
    var Cars;
    function getSize() {
        return new Cars(20, 30);
    }
    exports_1("getSize", getSize);
    return {
        setters:[],
        execute: function() {
            class Cars { // (1)
                constructor(len, wid) {
                    this.len = len;
                    this.wid = wid;
                }
            }
            exports_1("Cars", Cars);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

所以getSize最终使用的var Carsundefined

在 master 中,输出为(1)is 相反Cars = class Cars {,因此它分配给var CarsgetSize()工作。