【问题标题】:Typescript error "class is not a constructor"打字稿错误“类不是构造函数”
【发布时间】:2016-05-31 19:29:28
【问题描述】:

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

我已关注link 并尝试将目标环境更改为 ES5。它工作正常。有人能说出为什么它不适用于目标 ES6。

这是我的 TypeScript 代码:

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

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

错误是函数 getSize 中的“Cars 不是构造函数”。

顺便说一下,我正在尝试使用 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

【问题讨论】:

  • basarat 在链接问题中的回答建议不要使用--out。你在用--out吗?
  • 不...我没有使用任何此类...顺便说一句,我在浏览器中收到错误.........不是在编译时...
  • @BaradwajAryasomayajula:那么请同时发布抛出错误的编译代码
  • @Bergi:我发布了编译后的代码......我使用的是最新的打字稿版本......我在下面的链接sitepoint.com/the-es6-conundrum 中读到它说浏览器尚不支持 ES6 ...这是代码无法在浏览器中运行的原因吗?
  • @BaradwajAryasomayajula:这里的 ES6 没问题。这实际上只是编译器在这里输出了无法工作的无效代码 - 这是一个 TS 错误,正如 Arnavion 正确识别的那样。你应该接受他的回答。

标签: typescript ecmascript-6


【解决方案1】:

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

【讨论】:

  • 我在同一个问题中有 *.json 文件,女巫造成了这个问题,谢谢
  • 我有一个名为 base.class.ts 的文件和另一个名为 base.class 的文件(之前因疏忽而创建)。我删除了最后一个,这解决了我的问题。
  • 是的,刚刚在 tsconfig 中更改了 outDir。工作,谢谢
【解决方案2】:

(从the GH issue you opened.复制我的帖子)

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

所以getSize 最终使用var Cars,即undefined

在 master 中,(1) 的输出改为 Cars = class Cars {,因此它分配给 var CarsgetSize() 有效。

【讨论】:

  • 我之前一定说过...但是我在浏览器中遇到了这个问题,但在编译打字稿时却没有....
  • 我使用 tsc -t es6 -m 系统编译了代码...但是它仍然给我和上面一样的js...
【解决方案3】:

我不确定,但我认为这取决于 TypeScript 版本。

请尝试这样声明:

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

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

export { Cars };

【讨论】:

    猜你喜欢
    • 2017-03-03
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2017-01-29
    • 1970-01-01
    • 2022-01-15
    • 2019-04-13
    相关资源
    最近更新 更多