From c187fd84d197e2f29759a157c798538661d36079 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Fri, 11 Oct 2024 17:13:09 -0400 Subject: [PATCH] types: correct schema type inference when using nested typeKey like `type: { type: String }` Fix #14950 --- test/types/schema.test.ts | 18 ++++++++++++++++++ types/inferschematype.d.ts | 12 ++++++++++-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/test/types/schema.test.ts b/test/types/schema.test.ts index f1b9c3c0d0..ec20ce689e 100644 --- a/test/types/schema.test.ts +++ b/test/types/schema.test.ts @@ -1645,3 +1645,21 @@ function gh8389() { function gh14879() { Schema.Types.String.setters.push((val?: unknown) => typeof val === 'string' ? val.trim() : val); } + +async function gh14950() { + const SightingSchema = new Schema( + { + _id: { type: Schema.Types.ObjectId, required: true }, + location: { + type: { type: String, required: true }, + coordinates: [{ type: Number }] + } + } + ); + + const TestModel = model('Test', SightingSchema); + const doc = await TestModel.findOne().orFail(); + + expectType(doc.location!.type); + expectType(doc.location!.coordinates); +} diff --git a/types/inferschematype.d.ts b/types/inferschematype.d.ts index 07ee5087b3..a34c355f49 100644 --- a/types/inferschematype.d.ts +++ b/types/inferschematype.d.ts @@ -183,8 +183,16 @@ type TypeHint = T extends { __typehint: infer U } ? U: never; * @param {TypeKey} TypeKey A generic refers to document definition. */ type ObtainDocumentPathType = ResolvePathType< -PathValueType extends PathWithTypePropertyBaseType ? PathValueType[TypeKey] : PathValueType, -PathValueType extends PathWithTypePropertyBaseType ? Omit : {}, + PathValueType extends PathWithTypePropertyBaseType + ? PathValueType[TypeKey] extends PathWithTypePropertyBaseType + ? PathValueType + : PathValueType[TypeKey] + : PathValueType, + PathValueType extends PathWithTypePropertyBaseType + ? PathValueType[TypeKey] extends PathWithTypePropertyBaseType + ? {} + : Omit + : {}, TypeKey, TypeHint >;