Node 对 TypeScript 生成的 Javascript 中的某些内容不满意,我不知道为什么。这是代码
人.ts:
export module Models {
export class Person {
id: number;
firstName: string;
lastName: string;
constructor(f: string, l: string) {
this.firstName = f;
this.lastName = l;
}
public saySomething(): void {
console.log("my name is %s %s", this.firstName, this.lastName);
}
}
}
数据库.ts:
import P = module("Person");
export module Database {
export class DB {
public findPerson(id: number): P.Models.Person {
return new P.Models.Person("a", "b");
}
}
}
测试.ts:
var D = require("./DB");
var db = new D.Database.DB();
var p = db.findPerson(123);
p.saySomething();
它在 Javascript 中编译得很好,但是正在创建的 DB.js 文件似乎有问题。当我尝试在节点中运行 Test.js 时,我得到了这个:
$node Test.js
DB.js:2
(function (Database) {
^
TypeError: object is not a function
at Object.<anonymous> (DB.js:2:1)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:362:17)
at require (module.js:378:17)
at Object.<anonymous> (Test.js:1:73)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
它发生在导入 DB.js 期间。奇怪的是,如果我将 findPerson() 方法更改为返回字符串而不是 Person,它可以正常工作。它与创建 Person 对象有关。
这是Javascript:
(function (Models) {
var Person = (function () {
function Person(f, l) {
this.firstName = f;
this.lastName = l;
}
Person.prototype.saySomething = function () {
console.log("my name is %s %s", this.firstName, this.lastName);
};
return Person;
})();
Models.Person = Person;
})(exports.Models || (exports.Models = {}));
var P = require("./Person")
(function (Database) {
var DB = (function () {
function DB() { }
DB.prototype.findPerson = function (id) {
return new P.Models.Person("a", "b");
};
return DB;
})();
Database.DB = DB;
})(exports.Database || (exports.Database = {}));
var dbx = require("./DB")
var db1 = new dbx.Database.DB();
var p = db1.findPerson(123);
p.saySomething();