From 1204148b3be630c990758209f901206b4ca28e99 Mon Sep 17 00:00:00 2001 From: Dmitry Kirilyuk Date: Tue, 2 May 2023 17:25:02 +0300 Subject: [PATCH] Handle union types in FlattenMaps --- test/types/lean.test.ts | 19 ++++++++++++++++++- types/index.d.ts | 14 ++++++++++---- 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/test/types/lean.test.ts b/test/types/lean.test.ts index 975a7e2a0ed..b6f9e538038 100644 --- a/test/types/lean.test.ts +++ b/test/types/lean.test.ts @@ -1,4 +1,4 @@ -import { Schema, model, Document, Types, InferSchemaType, FlattenMaps } from 'mongoose'; +import { Schema, model, Types, InferSchemaType, FlattenMaps } from 'mongoose'; import { expectAssignable, expectError, expectType } from 'tsd'; function gh10345() { @@ -179,3 +179,20 @@ async function gh13345_2() { expectAssignable>(place); expectType>(place.images[0].description); } + +async function gh13345_3() { + const imageSchema = new Schema({ + url: { required: true, type: String } + }); + + const placeSchema = new Schema({ + images: { type: [imageSchema], default: undefined } + }); + + type Place = InferSchemaType; + + const PlaceModel = model('Place', placeSchema); + + const place = await PlaceModel.findOne().lean().orFail().exec(); + expectAssignable(place); +} diff --git a/types/index.d.ts b/types/index.d.ts index c42e7233375..2af1b24f539 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -594,12 +594,18 @@ declare module 'mongoose' { export type UpdateQuery = _UpdateQuery & AnyObject; export type FlattenMaps = { - [K in keyof T]: T[K] extends Map - ? Record : T[K] extends TreatAsPrimitives - ? T[K] : T[K] extends Types.DocumentArray - ? Types.DocumentArray> : FlattenMaps; + [K in keyof T]: FlattenProperty; }; + /** + * Separate type is needed for properties of union type (for example, Types.DocumentArray | undefined) to apply conditional check to each member of it + * https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types + */ + type FlattenProperty = T extends Map + ? Record : T extends TreatAsPrimitives + ? T : T extends Types.DocumentArray + ? Types.DocumentArray> : FlattenMaps; + export type actualPrimitives = string | boolean | number | bigint | symbol | null | undefined; export type TreatAsPrimitives = actualPrimitives | NativeDate | RegExp | symbol | Error | BigInt | Types.ObjectId | Buffer | Function;