Reputation: 679
When trying to calculate a virtual property model I get: Object is possibly 'null' If possible I would prefer not suppressing the typescript's strict rule.
import { Schema, model } from "mongoose";
const SymbolSchema = new Schema({
max: Number,
min: Number,
});
export interface Symbol {
max: number;
min: number;
}
export default model("Symbol", SymbolSchema);
SymbolSchema.virtual("diff").get(() => {
return this ? (this?.max - this?.min ): 0
// this error : Object is possibly 'undefined'.ts(2532)
});
also have checked this
but the ts(2532)
error occurs
so how to solve it?
Upvotes: 2
Views: 1900
Reputation: 22758
You shouldn't use this
and an arrow function together in this case because you need this
to be an instance of a model and not this whole module:
SymbolSchema.virtual("diff").get(function(this:Symbol) {
return this ? (this?.max - this?.min ): 0
// this error : Object is possibly 'undefined'.ts(2532)
});
Upvotes: 6