简体   繁体   中英

Typescript class.default is not a constructor

Creating an Angular2 app, I am facing the following problem, when calling the constructor of another class inside the constructor of first class.

First Class code

import SecondClass from './second-class'

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

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

Second Class code:

export class SecondClass {
    someOtherVar:string;

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

Would give me the error: ORIGINAL EXCEPTION: TypeError: second_class_1.default is not a constructor

Content of ./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

This is the compiled output from Typescript compiler

Error message implies that you used named export ( export class SecondClass {} ) in ./second-class (not default). So it means that your import should looks something like

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

There are some errors in the code :

  • missing {} from import

  • missing () from calling the constructor

  • missing this from accessing Class members

First Class code

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

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

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

Second Class code:

export class SecondClass {
    someOtherVar:string;

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

this is too late, but I just got the same error right now. Solution is export SecondClass as default so Second Class code will be:

export default class SecondClass {
    someOtherVar:string;

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

and import in other class with import SecondClass from './second-class'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM