Skip to content

Commit

Permalink
Merge pull request #12464 from Automattic/vkarpov15/gh-12319
Browse files Browse the repository at this point in the history
fix(types): add HydratedDocumentFromSchema to make it easier to pull inferred hydrated doc type
  • Loading branch information
vkarpov15 committed Sep 26, 2022
2 parents 55112dc + b59cbed commit 88ba7a1
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
1 change: 1 addition & 0 deletions .eslintrc.json
Expand Up @@ -25,6 +25,7 @@
"rules": {
"@typescript-eslint/triple-slash-reference": "off",
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/no-empty-function": "off",
"spaced-comment": [
"error",
"always",
Expand Down
26 changes: 26 additions & 0 deletions test/types/models.test.ts
Expand Up @@ -9,6 +9,7 @@ import {
UpdateQuery,
CallbackError,
HydratedDocument,
HydratedDocumentFromSchema,
LeanDocument,
Query,
UpdateWriteOpResult
Expand Down Expand Up @@ -494,3 +495,28 @@ async function gh12347() {
const replaceOneResult = await User.replaceOne({}, {});
expectType<UpdateWriteOpResult>(replaceOneResult);
}

async function gh12319() {
const projectSchema = new Schema(
{
name: {
type: String,
required: true
}
},
{
methods: {
async doSomething() {
}
}
}
);

const ProjectModel = model('Project', projectSchema);

type ProjectModelHydratedDoc = HydratedDocumentFromSchema<
typeof projectSchema
>;

expectType<ProjectModelHydratedDoc>(await ProjectModel.findOne().orFail());
}
6 changes: 6 additions & 0 deletions types/index.d.ts
Expand Up @@ -124,6 +124,12 @@ declare module 'mongoose' {

export type HydratedDocument<DocType, TMethodsAndOverrides = {}, TVirtuals = {}> = DocType extends Document ? Require_id<DocType> : (Document<unknown, any, DocType> & Require_id<DocType> & TVirtuals & TMethodsAndOverrides);

export type HydratedDocumentFromSchema<TSchema extends Schema> = HydratedDocument<
InferSchemaType<TSchema>,
ObtainSchemaGeneric<TSchema, 'TQueryHelpers'>,
ObtainSchemaGeneric<TSchema, 'TInstanceMethods'>
>;

export interface TagSet {
[k: string]: string;
}
Expand Down

0 comments on commit 88ba7a1

Please sign in to comment.