我正在幫助使用 MongoDB 來持久化資料的打字稿應用程式。我們正在嘗試做的一件事是擺脫any使用。
以下代碼用于定義貓鼬模式的一部分:
priceMax: {
max: 10000000,
min: 0,
required: function (this: FeePricing & Document) {
return this.priceMin === undefined;
},
type: Number,
validate: [
{
message: 'Max price cannot be lower than min price',
validator: function (v: number) {
if ((this as any).priceMax === null || (this as any).priceMax === undefined) return true;
return (this as any).priceMin ? v >= (this as any).priceMin : v >= 0;
},
},
{
message: 'Max price cannot be higher than 50000 for this feeType',
validator: function (v: number) {
return !(!feeTypesWithoutMaxLimit.includes((this as any).feeType) && v > 50000);
},
},
],
},
priceMin: {
max: 10000000,
min: 0,
required: function () {
return (this as any).priceMax === undefined;
},
type: Number,
validate: {
message: 'priceMin cannot be higher than priceMax',
validator: function (v: number) {
return (this as any).priceMax ? v <= (this as any).priceMax : v >= 0;
},
},
},
updatedAt: { type: Date },
updatedBy: { type: String },
我有點理解這些功能在做什么,但這里的型別讓我感到困惑。
我怎么能擺脫this as any?為什么不只使用FeePricing型別 - 例如(this as FeePricing)?FeePricing似乎 is 只是我的應用程式中的另一種型別 [,它具有priceMin和priceMax] 與Document界面相結合。來自ReactJS 的Document方法在這里有什么幫助?為什么需要它?是this在validate上面定義的型別中FeePricing & Document嗎?
謝謝
uj5u.com熱心網友回復:
this是您的驗證配置的背景關系。因為 TypeScript 無法推斷其型別(因為它可以更改),所以我建議您創建自己的自定義型別,例如FeePricing. 我不太確定您的當前FeePricing包含哪些屬性,因為它未包含在示例中,但我會如下所示:
interface FeePricing {
priceMin?: mongoose.Schema.Types.Number | null,
priceMax?: mongoose.Schema.Types.Number | null,
feeType?: mongoose.Schema.Types.Number | null,
}
然后你可以像這樣使用它:
(this as FeePricing).priceMax
屬性是可選的并且也是 null 的原因是因為我可以看到您的一些邏輯檢查它們是否是undefinedor null,因此這些型別將反映它們在運行時可能不存在并幫助您正確驗證。此外,如果FeePricing型別用于其他用途,您當然可以將此型別名稱更改為其他名稱。
要回答您關于 ReactJs 的問題Document,它不會為推斷 mongoose 配置型別添加任何幫助,并且可以真正洗掉。
uj5u.com熱心網友回復:
正如我在 Mongoose 中所理解的那樣,模式用于定義存盤在 MongoDB 中的檔案。如果我是正確的,您可以創建一個 Feepricing 的模型/介面并將其用作型別。
export interface FeePricing {
priceMax: number;
priceMin: number;
}
this是 FreePricing 物件。
希望這可以幫助
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/457940.html
