关于node.js:猫鼬”类型y上不存在属性x”错误-仍然有效

Mongoose “property x does not exist on type y” error - still works

在Mongoose中,尝试使用点表示法(model.attribute)时得到error TS2339: Property 'highTemp' does not exist on type 'Location',尽管代码仍按预期运行。在这里的注释中,我了解到使用model['attribute']不会产生任何错误。

能够在猫鼬中正确使用点符号的正确方法是什么?

背景:

location.model.ts

1
2
3
4
5
6
7
8
9
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

1
2
3
4
5
6
7
8
9
10
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中的点表示法。我应该怎么办?为每个模型明确定义接口听起来像是毫无意义的工作。


model方法接受一个接口(需要扩展Document),该接口可用于静态键入结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
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
}