使用Mongoose,我得到error TS2339: Property 'highTemp' does not exist on type 'Location'虽然代码仍然按预期工作,但尝试使用点符号( model.attribute )时, error TS2339: Property 'highTemp' does not exist on type 'Location' 。 在这里的评论中,我了解到使用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 。 我该怎么办? 明确定义每个模型的接口听起来像没有意义的工作..?
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..?
最满意答案
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 }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 }更多推荐
发布评论