Typescript error "class is not a constructor"

I am running the following typescript code in the ES6 target environment and it says that "Cars is not a constructor"

I have followed the link and tried changing the target environment to ES5. It is working fine. Can some one tell why it is not working for target ES6.

Here is my TypeScript code:

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

export function getSize(): Cars {
    return new Cars(20, 30);
};

Error is "Cars is not a constructor" in the function getSize.

By the way I am trying to load all the files with Systemjs.

By the way I am getting the error in the browser........ Not while compiling it...

Here is the compiled code of the above typescript....

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

(Copying my post from the GH issue you opened.)

This is a bug in TS 1.8.10 and fixed in master.

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

in 1.8.10 gives:

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

So getSize ends up using the var Cars which is undefined .

In master the output for (1) is instead Cars = class Cars { so it assigns to the var Cars and getSize() works.


I'm not sure but I think that this depends on the TypeScript version.

Please try declaring this like so:

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

export function getSize(): Cars {
    return new Cars(20, 30);
};

export { Cars };

Make sure you don't have .js and .ts files in the same directory. This can be caused by your IDE sometimes.

链接地址: http://www.djcxy.com/p/91946.html

上一篇: 如何访问我使用Gmail API的gmail帐户?

下一篇: Typescript错误“类不是构造函数”