Node对于TypeScript正在生成的Javascript中的某些内容并不满意,我无法弄清楚原因。这是代码
Person.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);
}
}
}
Database.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");
}
}
}
Test.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();
答案 0 :(得分:5)
在var P = require(“./ Person”)之后没有分号javascript认为比下一个(...)是函数的调用。但是你似乎在Database.ts中有它,所以Typescript可能会在编译中丢失一些分号。
答案 1 :(得分:0)
主要问题是您要导入名为Person
的模块,我认为您要导入包含名为Models
的类的Person
模块。
当您定位nodejs或其他CommonJS平台时,省略模块声明。
您还可以利用构造函数中的自动属性。
所以你会Models.ts
:
export class Person {
id: number;
constructor (public firstName: string, public lastName: string) {
}
public saySomething(): void {
console.log("my name is %s %s", this.firstName, this.lastName);
}
}
Database.ts
import models = module("Models");
export class DB {
public findPerson(id: number): models.Person {
return new models.Person("a", "b");
}
}