【问题标题】:Mongoose "property x does not exist on type y" error - still worksMongoose“y 类型不存在属性 x”错误 - 仍然有效
【发布时间】:2018-07-28 12:38:17
【问题描述】:

对于 Mongoose,我在尝试使用点表示法 (model.attribute) 时得到 error TS2339: Property 'highTemp' does not exist on type 'Location',尽管代码仍然按预期工作。在 cmets 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 上产生 TS2339 错误。我首选的使用模型属性的方法是使用location.highTemp 中的点表示法。我该怎么办?为每个模型显式定义接口听起来毫无意义..?

【问题讨论】:

    标签: node.js typescript mongoose


    【解决方案1】:

    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
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-14
      • 2021-12-15
      • 2020-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多