【发布时间】:2019-03-27 14:57:06
【问题描述】:
我在使用 mongoose 和 typescript 定义模式时遇到了两个问题。 这是我的代码:
import { Document, Schema, Model, model} from "mongoose";
export interface IApplication {
id: number;
name: string;
virtualProperty: string;
}
interface IApplicationModel extends Document, IApplication {} //Problem 1
let ApplicationSchema: Schema = new Schema({
id: { type: Number, required: true, index: true, unique: true},
name: { type: String, required: true, trim: true },
});
ApplicationSchema.virtual('virtualProperty').get(function () {
return `${this.id}-${this.name}/`; // Problem 2
});
export const IApplication: Model<IApplicationModel> = model<IApplicationModel>("Application", ApplicationSchema);
首先:
- 这一行的问题 1
interface IApplicationModel extends Document, IApplication {}
Typescript 告诉我:
error TS2320: Interface 'IApplicationModel' cannot simultaneously extend types 'Document' and 'IApplication'.
Named property 'id' of types 'Document' and 'IApplication' are not identical.
那么如何改变id属性的定义呢?
-
问题 2 在内部函数中(
virtualProperty的 getter):return `${this.id}-${this.name}/; // 问题2
错误是:
error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.
this的类型如何定义?
【问题讨论】:
标签: javascript typescript mongoose mongoose-schema