2

这个打字稿:

export enum UID {
    FACTORY,
    ROBOT
}

编译成这个 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;

我不得不承认代码对我来说似乎相当晦涩,但我相信 tsc 编译器知道它在做什么。不幸的是,javascript无法执行。nodejs 抱怨说:

(函数(UID){

^ 类型错误:对象不是函数

at ...

我做错了什么?

更新:Matt B. 已经解决了这个问题。这是 typescript 编译器中的一个已知错误。tsc 无法在 require 语句后插入分号,这可能会导致奇怪的错误。手动将分号添加到我的代码中解决了这个问题。这是 codeplex 问题的链接:http: //typescript.codeplex.com/workitem/364

更新2: 对于那些遇到同样错误的人。您可以手动插入缺少的分号,但这不是一个非常舒适的解决方案,因为您必须在每次编译后执行此操作。我注意到这个问题只发生在枚举上。项目中有很多其他模块,没有一个模块导致这个错误。显然,类定义并没有被前面缺少的分号“伤害”。只需将枚举的定义移到您的一个类定义后面,错误就会消失。将枚举移到接口后面是不够的,因为接口没有直接等价物,只是被编译器删除

4

3 回答 3

6

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

于 2013-03-06T17:26:57.630 回答
0

在你的 Javascript 中你应该有类似的东西

var exports = exports || {};

(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;
于 2013-03-06T17:15:55.573 回答
0

I tried and I have the same problem - I assume that the missing exports variables should be generated by the JavaScript code used to load the module when you do

import XXXX = module("XXXX");

that generates this JavaScript:

var XXXX = require("./XXXX")

and I think Matt B. is right and the problem there is the missing semi-colon after require(), that messes things up afterwards.

A fix is to place the enumeration declaration in a module:

module Test {

    export enum UID {
      FACTORY,
      ROBOT
    }

}

that generates:

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

in this way the exports variable is no longer needed.

于 2013-03-06T17:51:36.940 回答