我开始了学习 typescript 的新冒险。我拿了一个当然是用 javascript 编写的 nodejs 项目,我正在将它转换成 typescript 。我的想法是看到所有的好处并了解问题在哪里,我应该使用哪种模式等等。
该项目使用带有 mongoose javascript 库的 mongodb 数据库,我正在努力研究 typescript 如何转译代码。简单来说:我丢失了 this 引用。
这是导致问题的好例子。
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 项目。
以下是我如何尝试简单的 typescript 转换:
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,但我真的很喜欢它。
最佳答案
试试这个:
var personSchema = new mongoose.Schema({
created: {
type: Date,
default: Date.now
},
updated: {
type: Date
}
saveHandler(next) {
// Make sure updated holds the current date/time
this.updated = new Date();
next();
}
});
personSchema.pre('save', personSchema.saveHandler);
关于javascript - 将 mongoose javascript 代码转换为 typescript。此引用丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37132039/