我想创建一个函数,它将 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();
任何更简单的解决方案将受到赞赏和接受!谢谢
1条答案
按热度按时间pu3pd22g1#
对于 mongoose v6.11.1 和 v7.1.0,您可以使用
HydratedDocument<Blog>
类型来表示一个水合的Mongoose文档,具有方法、虚拟值和其他Mongoose特定的特性。
参见doc
我使用
expect-type
来检查HydratedDocument<Blog>
类型是否与InstanceType<typeof BlogModel>
类型匹配。