Reputation: 1339
With Mongoose, I get error TS2339: Property 'highTemp' does not exist on type 'Location'
when trying to use dot notation (model.attribute
) although the code still works as intended. In the comments here I learned that using model['attribute']
yields no error.
What is the proper way to be able to use dot notation with Mongoose without errors?
Background:
location.model.ts
import mongoose = require('mongoose');
export const LocationSchema = new mongoose.Schema({
name: String,
lowTemp: Number,
highTemp: Number,
});
export const Location = mongoose.model('Location', LocationSchema);
data.util.ts
import { Location } from '../models/location.model';
function temperatureModel(location: Location): number {
const highTemp = location.highTemp;
const lowTemp = location['lowTemp'];
// Do the math...
return something;
}
Building the above yields the TS2339 error on highTemp
but not on lowTemp
. My preferred method of using model attributes would be with dot notation as in location.highTemp
. What should I do? Explicitly defining interfaces for every model sounds like pointless work..?
Upvotes: 1
Views: 3150
Reputation: 249466
The model
method accepts an interface (which needs to extends Document
) which can be used to statically type the result:
export interface Location extends mongoose.Document {
name: string,
lowTemp: number,
highTemp: number,
}
export const Location = mongoose.model<Location>('Location', LocationSchema);
// Usage
function temperatureModel(location: Location): number {
const highTemp = location.highTemp; // Works
const lowTemp = location.lowTemp; // Works
}
Upvotes: 3