typescript mongoose模型示例类型

cld4siwp  于 2023-05-19  发布在  TypeScript
关注(0)|答案(1)|浏览(262)

我想创建一个函数,它将 Mongoose 模型示例作为唯一的参数。为此,我需要指定类型;像这样的东西

function takeModelInstance(instance: TypeIDontKnowHowToSpecifiy) {
  // body doesn't matter
}

这是我的Schema和Model创建代码:

interface Blog {
  title: string,
}

const blogSchema = new mongoose.Schema<Blog>({
  title: String,
});

const BlogModel = mongoose.model('Blog', blogSchema);

我的方法:

// type is inferred but doesn't help as output is very impractical:
//   mongoose.Model<Blog, {}, {}, {}, mongoose.Document<unknown, {}, Blog> & Omit<Blog & { _id: mongoose.Types.ObjectId; }, never>, any>
const demo1 = new BlogModel();

// does not produce an error straight away, but autocompletion such as `demo.title` doesn't work so something is wrong
const demo2: typeof BlogModel = new BlogModel();

**编辑:**我用

const demo3: InstanceType<typeof BlogModel> = new BlogModel();

任何更简单的解决方案将受到赞赏和接受!谢谢

pu3pd22g

pu3pd22g1#

对于 mongoose v6.11.1v7.1.0,您可以使用HydratedDocument<Blog>类型来
表示一个水合的Mongoose文档,具有方法、虚拟值和其他Mongoose特定的特性。
参见doc
我使用expect-type来检查HydratedDocument<Blog>类型是否与InstanceType<typeof BlogModel>类型匹配。

import mongoose, { HydratedDocument } from 'mongoose';
import { expectTypeOf } from 'expect-type';

interface Blog {
  title: string,
}

const blogSchema = new mongoose.Schema<Blog>({
  title: String,
});

const BlogModel = mongoose.model<Blog>('Blog', blogSchema);

function takeModelInstance(instance: HydratedDocument<Blog>) {

}

const demo3: InstanceType<typeof BlogModel> = new BlogModel();

expectTypeOf(demo3).toMatchTypeOf<HydratedDocument<Blog>>() // type check pass

// The expanded TS type of HydratedDocument<Blog> is:
// mongoose.Document<unknown, any, Blog> & Omit<Blog & {
//     _id: mongoose.Types.ObjectId;
// }, never>

相关问题