【发布时间】:2016-09-05 01:10:07
【问题描述】:
我开始了学习打字稿的新冒险。我拿了一个用 javascript 编写的 nodejs 项目,并将其转换为打字稿。我的想法是看到所有好处并了解问题出在哪里,我应该使用哪种模式等等。
该项目将 mongodb 数据库与 mongoose javascript 库一起使用,我正在努力解决 typescript 如何转译代码。简而言之:我失去了这个参考。
这是一个很好的例子,会导致问题。
var personSchema = new mongoose.Schema({
created: {
type: Date,
default: Date.now
},
updated:{
type: Date,
},
});
personSchema.pre('save', function(next) {
// Make sure updated holds the current date/time
this.updated = new Date();
next();
});
var Person = mongoose.model('Person', personSchema);
在预保存功能中有一个 this 引用。这是具有更新属性的当前人员的引用。一切顺利。我在不同的例子中看到了这种模式
这是我第一次从事 nodejs 项目。
这是我尝试简单的打字稿转换的方法:
interface IPerson extends mongoose.Document{
created:Date;
updated:Date;
}
var personSchema = new mongoose.Schema({
created: {
type: Date,
default: Date.now
},
updated: {
type: Date
}
});
personSchema.pre('save', (next) => {
// Make sure updated holds the current date/time
this.updated = new Date();
next();
});
export = mongoose.model<IPerson>('Person', personSchema);
在 typescript 转译代码后 this 与 _this 交换。在文件顶部您会看到 var _this = this;。这是错误的。新的 javascript 文件失去了对 person 对象的引用。
有人可以帮助我如何正确地将 javascript 转换为 typescript 吗?我应该如何解决这类问题?有什么规律吗?
我的第一印象是有时不是直接将 javascript 转换为 typescript,但我真的很喜欢。
【问题讨论】:
标签: javascript mongodb mongoose typescript