带打字稿的猫鼬架构-设计错误

时间:2018-10-23 11:25:04

标签: javascript typescript mongoose mongoose-schema

我在使用猫鼬和打字稿定义架构时遇到两个问题。 这是我的代码:

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 {}

打字稿告诉我:

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的获取者):

    返回`$ {this.id}-$ {this.name} /; //问题2

错误是:

error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.

如何定义this的类型?

1 个答案:

答案 0 :(得分:0)

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

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

this