diff --git a/test/types/populate.test.ts b/test/types/populate.test.ts index eefddc09fee..f354eaca17a 100644 --- a/test/types/populate.test.ts +++ b/test/types/populate.test.ts @@ -170,12 +170,14 @@ function gh11503() { const User = model('friends', userSchema); User.findOne({}).populate('friends').then(user => { - expectType(user?.friends[0]); + if (!user) return; + expectType(user?.friends[0]); expectError(user?.friends[0].blocked); expectError(user?.friends.map(friend => friend.blocked)); }); User.findOne({}).populate<{ friends: Friend[] }>('friends').then(user => { + if (!user) return; expectAssignable(user?.friends[0]); expectType(user?.friends[0].blocked); const firstFriendBlockedValue = user?.friends.map(friend => friend)[0]; @@ -197,4 +199,32 @@ function gh11544() { User.findOne({}).populate({ path: 'friends', strictPopulate: false }); User.findOne({}).populate({ path: 'friends', strictPopulate: true }); User.findOne({}).populate({ path: 'friends', populate: { path: 'someNestedPath', strictPopulate: false } }); +} + +async function _11532() { + interface IParent { + name: string; + child: Types.ObjectId; + } + interface IChild { + name: string; + } + + const parentSchema = new Schema( + { + name: { type: String, required: true }, + child: { type: Schema.Types.ObjectId, ref: 'Child', required: true } + }); + + const parent = model('Parent', parentSchema); + + const populateQuery = parent.findOne().populate<{ child: IChild }>('child'); + const populateResult = await populateQuery; + const leanResult = await populateQuery.lean(); + + if (!populateResult) return; + expectType(populateResult.child.name); + + if (!leanResult) return; + expectType(leanResult.child.name); } \ No newline at end of file diff --git a/types/index.d.ts b/types/index.d.ts index e4ee8c10456..b1a18815483 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -1471,7 +1471,7 @@ declare module 'mongoose' { type QueryWithHelpers = Query & THelpers; - type UnpackedIntersection = T extends (infer A)[] + type UnpackedIntersection = T extends null ? null : T extends (infer A)[] ? (Omit & U)[] : keyof U extends never ? T @@ -1776,8 +1776,8 @@ declare module 'mongoose' { polygon(path: string, ...coordinatePairs: number[][]): this; /** Specifies paths which should be populated with other documents. */ - populate(path: string | string[], select?: string | any, model?: string | Model, match?: any): QueryWithHelpers, DocType, THelpers, RawDocType>; - populate(options: PopulateOptions | (PopulateOptions | string)[]): QueryWithHelpers, DocType, THelpers, RawDocType>; + populate>(path: string | string[], select?: string | any, model?: string | Model, match?: any): QueryWithHelpers; + populate>(options: PopulateOptions | (PopulateOptions | string)[]): QueryWithHelpers; /** Get/set the current projection (AKA fields). Pass `null` to remove the current projection. */ projection(): ProjectionFields | null;