【问题标题】:Set the return type of toObject method设置 toObject 方法的返回类型
【发布时间】:2019-06-14 10:54:26
【问题描述】:

我正在尝试在 Mongoose 中设置 toObject 方法的返回类型,尽管我不确定这是否可行。

使用泛型,可以设置 Document 对象的属性,该对象从使用 Mongoose 的查询返回,但这些对象的 getter 和 setter 通常在访问时运行许多验证代码,这是我想要的在某些情况下喜欢避免。

那些Document 对象具有返回等效匿名对象的toObject 方法,这就是我正在使用的,但那些返回的对象具有any 类型。我想在SchemaModel 定义中设置这些对象的类型,这样我就不必在每次查询时都使用类型断言。

目前我的代码如下所示:

import mongoose, { Schema, Document } from 'mongoose'

interface User {
    username: string,
    email:    string,
    password: string,
}

const UserSchema = new Schema({
    username: { type: String, required: true },
    email:    { type: String, required: true },
    password: { type: String, required: true },
})

const UserModel = mongoose.model<User & Document>('User', UserSchema)

export { User, UserModel }

有了这个,我可以使用以下代码执行查询:

const userDocument = await UserModel.findById(id)
const userObj      = userDocument && userDocument.toObject()

虽然userDocument 属于User extends Document 类型,但userObj 属于any 类型。我想将其设置为 User 类型。

【问题讨论】:

    标签: typescript mongoose


    【解决方案1】:

    遗憾的是,Mongoose 中的 toObject 方法被键入为“any”,这意味着唯一的选择是增加“toObject”方法并覆盖类型 |或 |用冒号键入 userObj。

    这是猫鼬类型中 toObject 的签名。

     toObject(options?: DocumentToObjectOptions): any;
    

    简单的解决方法是这样做......

    const userObj: undefined | User = userDocument && userDocument.toObject()
    

    希望这会有所帮助,我知道这不是一个“理想”的解决方案,但我会说与 Typescript gitter 或DefiniteTyped mongoose 团队合作,让他们在内部修复打字。

    如果还有其他问题,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 2017-02-15
      • 2021-10-19
      • 1970-01-01
      • 2013-11-08
      • 1970-01-01
      相关资源
      最近更新 更多