From 7bc60e9faad760d031aef2a91d63de4d937905db Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Mon, 19 Aug 2024 10:51:43 -0400 Subject: [PATCH] types: make toObject() and toJSON() not generic by default to avoid type widening Fix #12883 --- test/types/schema.test.ts | 9 ++++++--- types/document.d.ts | 5 ++++- types/inferrawdoctype.d.ts | 5 ++++- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/test/types/schema.test.ts b/test/types/schema.test.ts index 2d946adc93..448858750c 100644 --- a/test/types/schema.test.ts +++ b/test/types/schema.test.ts @@ -22,6 +22,7 @@ import { model, ValidateOpts } from 'mongoose'; +import { IsPathRequired } from '../../types/inferschematype'; import { expectType, expectError, expectAssignable } from 'tsd'; import { ObtainDocumentPathType, ResolvePathType } from '../../types/inferschematype'; @@ -1502,16 +1503,18 @@ function gh13772() { const schemaDefinition = { name: String, docArr: [{ name: String }] - }; + } as const; const schema = new Schema(schemaDefinition); + + const TestModel = model('User', schema); type RawDocType = InferRawDocType; expectAssignable< - { name?: string | null, docArr?: Array<{ name?: string | null }> } + { name?: string | null, docArr?: Array<{ name?: string | null }> | null } >({} as RawDocType); - const TestModel = model('User', schema); const doc = new TestModel(); expectAssignable(doc.toObject()); + expectAssignable(doc.toJSON()); } function gh14696() { diff --git a/types/document.d.ts b/types/document.d.ts index c0fb558924..6fb01c910c 100644 --- a/types/document.d.ts +++ b/types/document.d.ts @@ -259,11 +259,14 @@ declare module 'mongoose' { set(value: string | Record): this; /** The return value of this method is used in calls to JSON.stringify(doc). */ + toJSON(options?: ToObjectOptions & { flattenMaps?: true }): FlattenMaps>; + toJSON(options: ToObjectOptions & { flattenMaps: false }): Require_id; toJSON>(options?: ToObjectOptions & { flattenMaps?: true }): FlattenMaps; toJSON>(options: ToObjectOptions & { flattenMaps: false }): T; /** Converts this document into a plain-old JavaScript object ([POJO](https://masteringjs.io/tutorials/fundamentals/pojo)). */ - toObject>(options?: ToObjectOptions): Require_id; + toObject(options?: ToObjectOptions): Require_id; + toObject(options?: ToObjectOptions): Require_id; /** Clears the modified state on the specified path. */ unmarkModified(path: T): void; diff --git a/types/inferrawdoctype.d.ts b/types/inferrawdoctype.d.ts index e2b1d52b6b..5ef52e1325 100644 --- a/types/inferrawdoctype.d.ts +++ b/types/inferrawdoctype.d.ts @@ -1,4 +1,5 @@ import { + IsPathRequired, IsSchemaTypeFromBuiltinClass, RequiredPaths, OptionalPaths, @@ -14,7 +15,9 @@ declare module 'mongoose' { [ K in keyof (RequiredPaths & OptionalPaths) - ]: ObtainRawDocumentPathType; + ]: IsPathRequired extends true + ? ObtainRawDocumentPathType + : ObtainRawDocumentPathType | null; }, TSchemaOptions>; /**