带有 Typescript 的 Mongoose Schema - 设计错误

Posted

技术标签:

【中文标题】带有 Typescript 的 Mongoose Schema - 设计错误【英文标题】:Mongoose Schema with Typescript - Design errors 【发布时间】: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的类型如何定义?

【问题讨论】:

【参考方案1】:

问题 #1:由于IApplicationModel 扩展了接口DocumentIApplication,它们声明了具有不同类型的id 属性(分别为anynumber),TypeScript 不知道id IApplicationModel 的属性应该是 anynumber 类型。您可以通过使用所需类型重新声明 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) ); 修复它

【讨论】:

请在您的回答中提供更多详细信息。正如目前所写的那样,很难理解您的解决方案。

以上是关于带有 Typescript 的 Mongoose Schema - 设计错误的主要内容,如果未能解决你的问题,请参考以下文章