【问题标题】:Mongoose Schema with Typescript - Design errors带有 Typescript 的 Mongoose Schema - 设计错误
【发布时间】: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


    【解决方案1】:

    问题 #1:由于IApplicationModel 扩展了接口Document 和IApplication,它们声明了具有不同类型的id 属性(分别为any 和number),TypeScript 不知道id IApplicationModel 的属性应该是 any 或 number 类型。您可以通过使用所需类型重新声明 IApplicationModel 中的 id 属性来解决此问题。 (为什么要声明一个单独的 IApplication 接口,而不是仅仅声明 IApplicationModel 来扩展 Document 的所有属性?)

    问题#2:只需向函数声明this 特殊参数,如下所示。

    import { Document, Schema, Model, model} from "mongoose";
    
    export interface IApplication {
        id: number;
        name: string;
        virtualProperty: string;
    }
    
    interface IApplicationModel extends Document, IApplication {
        id: number;
    }
    
    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 (this: IApplicationModel) {
        return `${this.id}-${this.name}/`;
    });
    export const IApplication: Model<IApplicationModel> = model<IApplicationModel>("Application", ApplicationSchema);
    

    【讨论】:

      【解决方案2】:

      对于问题 2:只需将 this 声明为 any :.get(function (this: any) {}); 修复它

      【讨论】:

      • 请在您的回答中提供更多详细信息。正如目前所写的那样,很难理解您的解决方案。
      猜你喜欢
      • 2022-01-07
      • 2021-09-09
      • 1970-01-01
      • 2017-12-13
      • 2018-10-09
      • 1970-01-01
      • 2017-08-12
      • 2019-03-12
      • 2021-10-08
      相关资源
      最近更新 更多