diff --git a/test/types/docArray.test.ts b/test/types/docArray.test.ts index 78650845ba..17ab708a96 100644 --- a/test/types/docArray.test.ts +++ b/test/types/docArray.test.ts @@ -162,3 +162,20 @@ function gh14469() { const jsonNames = doc?.names[0]?.toJSON(); expectType(jsonNames?.firstName); } + +function gh15041() { + const subDoc = { + name: { type: String, required: true }, + age: { type: Number, required: true } + }; + + const testSchema = new Schema({ + subdocArray: { type: [subDoc], required: true } + }); + + const TestModel = model('Test', testSchema); + + const doc = new TestModel({ subdocArray: [{ name: 'John', age: 30 }] }); + type TestModelDoc = ReturnType<(typeof TestModel)['hydrate']> + expectType(doc.subdocArray.splice(0, 1, { name: 'Bill' })); +} diff --git a/types/types.d.ts b/types/types.d.ts index 194917d69e..503a9b2c9f 100644 --- a/types/types.d.ts +++ b/types/types.d.ts @@ -60,19 +60,21 @@ declare module 'mongoose' { class Decimal128 extends mongodb.Decimal128 { } - class DocumentArray extends Types.Array, any, T> & T> { + class DocumentArray = Types.Subdocument, any, T> & T> extends Types.Array { /** DocumentArray constructor */ constructor(values: AnyObject[]); isMongooseDocumentArray: true; /** Creates a subdocument casted to this schema. */ - create(obj: any): T extends Types.Subdocument ? T : Types.Subdocument> & T; + create(obj: any): THydratedDocumentType; /** Searches array items for the first document with a matching _id. */ - id(id: any): (T extends Types.Subdocument ? T : Types.Subdocument> & T) | null; + id(id: any): THydratedDocumentType | null; push(...args: (AnyKeys & AnyObject)[]): number; + + splice(start: number, deleteCount?: number, ...args: (AnyKeys & AnyObject)[]): THydratedDocumentType[]; } class Map extends global.Map {