0
votes

I am running into a strange (to me) error when trying to run the code specified below. The code compiles fine, but when I run it, node returns this error:

<location>/C.js:11
    _super.call(this, "C");
           ^
TypeError: undefined is not a function
    at new C (<location>/C.js:11:16)
    at Function.B.factory (<location>/B.js:15:17)
    at Function.Test.test (<location>/Test.js:6:18)
    at Object.<anonymous> (<location>/app.js:2:6)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)

Compile command: tsc --module commonjs -t ES5 app.ts

Run with: node app.js

Obviously I am new to both Typescript and Javascript, but I just can't see why this would fail. I have looked around for a solution but although this seems to be a common issue, I have come up empty for my particular problem. Can anyone shed some light on as to why this is happening? Here are the files:

A.ts

class A {
    constructor(private name: string) {}
}
export = A;

B.ts

import A = require('./A');
import C = require('./C');

class B extends A {
    constructor(value: string) {
        super(value);
    }
    public static factory() {
        var a: A = new C();
        return a;
    }
}
export = B;

C.ts

import B = require('./B');

class C extends B {
    constructor() {
        super("C");
    }
}
export = C;

Test.ts

import B = require('./B');

class Test {
    public static test() {
        return B.factory();
    }
}
export = Test;

app.ts

///<reference path='./typings/node/node.d.ts' />
import Test = require('./Test');
Test.test();

In order to save some space here, I pastebinned the generated javascript code. It can be found here if you're interested: javascript dump

1

1 Answers

3
votes

This is because you have a circular dependency. C depends on B and B depends on C. Therefore B is undefined according to spec. https://nodejs.org/api/modules.html#modules_cycles