使用Mongoose,我在尝试使用点表示法(error TS2339: Property 'highTemp' does not exist on type 'Location'
)时得到model.attribute
,尽管代码仍然按预期工作。在评论here中,我了解到使用model['attribute']
不会产生任何错误。
能够在没有错误的情况下使用点符号与Mongoose的正确方法是什么?
背景:
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;
}
构建上述内容会在highTemp
上产生TS2339错误,但不会在lowTemp
上产生错误。我使用模型属性的首选方法是使用点符号,如location.highTemp
中所示。我该怎么办?明确定义每个模型的接口听起来像毫无意义的工作..?
答案 0 :(得分:3)
model
方法接受一个接口(需要扩展Document
),可用于静态输入结果:
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
}