首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >带有Typescript设计错误的Mongoose模式

带有Typescript设计错误的Mongoose模式
EN

Stack Overflow用户
提问于 2018-10-23 19:25:04
回答 2查看 705关注 0票数 0

我有两个使用mongoose和typescript定义模式的问题。下面是我的代码:

代码语言:javascript
代码运行次数:0
运行
复制
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的getter):

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

错误是:

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

如何定义this的类型

EN

回答 2

Stack Overflow用户

发布于 2018-10-24 07:34:50

问题#1:由于IApplicationModel扩展了DocumentIApplication接口,这两个接口声明了不同类型的id属性(分别为anynumber ),因此TypeScript不知道IApplicationModelid属性应该是any类型还是<代码>D9类型。您可以通过使用所需的类型重新声明IApplicationModel中的id属性来修复此问题。(为什么要声明一个单独的IApplication接口,而不是只声明用所有属性扩展DocumentIApplicationModel?)

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

代码语言:javascript
代码运行次数:0
运行
复制
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);
票数 0
EN

Stack Overflow用户

发布于 2021-09-08 16:15:55

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52947886

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档