Typescript class.default不是构造函数

时间:2016-04-24 21:55:14

标签: javascript typescript

创建一个Angular2应用程序时,我在第一个类的构造函数中调用另一个类的构造函数时遇到以下问题。

头等舱代码

import SecondClass from './second-class'

export class FirstClass {
    someVar:string;
    secondClass:SecondClass;

    constructor(firstClass?: FirstClass) {
        someVar='test';
        secondClass= new SecondClass;
    }
}

第二类代码:

export class SecondClass {
    someOtherVar:string;

    constructor(secondClass?:SecondClass) {
        someOtherVar='test';
    }
}

会给我错误:ORIGINAL EXCEPTION:TypeError:second_class_1.default不是构造函数

./second-class的内容

System.register([], function(exports_1, context_1) {
    "use strict";
    var __moduleName = context_1 && context_1.id;
    var SecondClass;
    return {
        setters:[],
        execute: function() {
            SecondClass = (function () {
                function SecondClass(secondClass) {
                    this.someOtherVar='test';
                }
                return SecondClass;
            }());
            exports_1("SecondClass", SecondClass);
        }
    }
});
//# sourceMappingURL=second-class.js.map

这是Typescript编译器的编译输出

3 个答案:

答案 0 :(得分:14)

错误消息表示您在export class SecondClass {}中使用了命名导出(./second-class)(非默认值)。所以这意味着您的导入应该类似于

import {SecondClass} from './second-class'

答案 1 :(得分:5)

代码中存在一些错误:

  • 从导入中删除{}

  • 在调用构造函数

  • 时缺少()
  • 缺少this访问班级成员

头等舱代码

import {SecondClass} from './second-class'

export class FirstClass {
    someVar:string;
    secondClass:SecondClass;

    constructor(firstClass?: FirstClass) {
        this.someVar='test';
        this.secondClass= new SecondClass();
    }
}

第二类代码:

export class SecondClass {
    someOtherVar:string;

    constructor(secondClass?:SecondClass) {
        this.someOtherVar='test';
    }
}

答案 2 :(得分:0)

这太晚了,但我现在也遇到了同样的错误。解决方案是默认导出SecondClass,因此第二类代码将是:

export default class SecondClass {
    someOtherVar:string;

    constructor(secondClass?:SecondClass) {
        this.someOtherVar='test';
    }
}

并使用import SecondClass from './second-class'

导入其他课程