javascriptnode.jstypescript

Typescript generated JavaScript has a function that is not a function


This typescript:

export enum UID {
    FACTORY,
    ROBOT
}

compiles to this javascript:

(function (UID) {
    UID._map = [];
    UID._map[0] = "FACTORY";
    UID.FACTORY = 0;
    UID._map[1] = "ROBOT";
    UID.ROBOT = 1;
})(exports.UID || (exports.UID = {}));
var UID = exports.UID;

I have to admit that the code seems rather obscure to me but I trusted the tsc compiler to know what it's doing. Unfortunately the javascript can't be executed. nodejs complains that:

(function (UID) {

^ TypeError: object is not a function

at ...

What have I done wrong ?

UPDATE: Matt B. has solved the problem. This is a known bug in the typescript compiler. tsc fails to insert semicolons after require statements, this can lead to strange errors. Manually adding the semicolons to my code solved the problem. Here's the link to the codeplex issue: http://typescript.codeplex.com/workitem/364

UPDATE 2: for those of you that experience the same error. You can insert the missing semicolons manually but that is not a very comfortable solution since you have to do this after every compilation. I noted that the problem only occurs with the enum. There are lots of other modules in the project and none of them have caused this error. Apparently a class definition is not "harmed" by the missing semicolons in front of it. Just move the definition of the enum behind one of your class definitions and the error should disappear. It's not sufficient to move the enum behind an interface since interfaces have no direct equivalent and are just deleted by the compiler


Solution

  • I think this is the same issue as described here -- which turned out to be due to a missing semicolon after a require() statement:

    Typescript generating javascript that doesn't work

    Is there a line like this in another compiled file?

    var UID = require('UID')

    If so, try adding a semicolon at the end:

    var UID = require('UID');

    This appears to be a TypeScript bug; here's the bug report (vote it up!): http://typescript.codeplex.com/workitem/364