我在 js 中使用 schema.virtual 屬性,但現在我想將它與 tyescript 一起使用并出現錯誤。這是我的代碼
UserSchema.virtual('fullname').get(function () {
return `${this.firstName} ${this.lastName}`
});
我正面臨這個錯誤
this' implicitly has type 'any' because it does not have a type annotation.
uj5u.com熱心網友回復:
有一些解決方案可以解決這個特定問題,例如宣告一個用于 typing的介面this,但根據我的經驗,這會產生其他問題(其中一個doc.fullname會導致錯誤,因為 TS 不夠聰明,無法知道fullname已添加為一個虛擬)。
解決這個問題的最簡單方法是使 virtuals 成為 Schema 宣告的一部分:
const UserSchema = new mongoose.Schema({
firstName : String,
lastName : String,
...
}, {
virtuals : {
fullname : {
get() {
return `${this.firstName} ${this.lastName}`;
}
}
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/510356.html
上一篇:NodeJS陣列未填滿
