Skip to content

Commit 891931b

Browse files
authored
Merge pull request Automattic#15085 from Automattic/vkarpov15/Automatticgh-15041
types: add splice() to DocumentArray to allow adding partial objects with splice()
2 parents 36fb91a + 3ef8901 commit 891931b

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

test/types/docArray.test.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,3 +162,20 @@ function gh14469() {
162162
const jsonNames = doc?.names[0]?.toJSON();
163163
expectType<string>(jsonNames?.firstName);
164164
}
165+
166+
function gh15041() {
167+
const subDoc = {
168+
name: { type: String, required: true },
169+
age: { type: Number, required: true }
170+
};
171+
172+
const testSchema = new Schema({
173+
subdocArray: { type: [subDoc], required: true }
174+
});
175+
176+
const TestModel = model('Test', testSchema);
177+
178+
const doc = new TestModel({ subdocArray: [{ name: 'John', age: 30 }] });
179+
type TestModelDoc = ReturnType<(typeof TestModel)['hydrate']>
180+
expectType<TestModelDoc['subdocArray'][0][]>(doc.subdocArray.splice(0, 1, { name: 'Bill' }));
181+
}

types/types.d.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,19 +60,21 @@ declare module 'mongoose' {
6060

6161
class Decimal128 extends mongodb.Decimal128 { }
6262

63-
class DocumentArray<T> extends Types.Array<T extends Types.Subdocument ? T : Types.Subdocument<InferId<T>, any, T> & T> {
63+
class DocumentArray<T, THydratedDocumentType extends Types.Subdocument<any> = Types.Subdocument<InferId<T>, any, T> & T> extends Types.Array<THydratedDocumentType> {
6464
/** DocumentArray constructor */
6565
constructor(values: AnyObject[]);
6666

6767
isMongooseDocumentArray: true;
6868

6969
/** Creates a subdocument casted to this schema. */
70-
create(obj: any): T extends Types.Subdocument ? T : Types.Subdocument<InferId<T>> & T;
70+
create(obj: any): THydratedDocumentType;
7171

7272
/** Searches array items for the first document with a matching _id. */
73-
id(id: any): (T extends Types.Subdocument ? T : Types.Subdocument<InferId<T>> & T) | null;
73+
id(id: any): THydratedDocumentType | null;
7474

7575
push(...args: (AnyKeys<T> & AnyObject)[]): number;
76+
77+
splice(start: number, deleteCount?: number, ...args: (AnyKeys<T> & AnyObject)[]): THydratedDocumentType[];
7678
}
7779

7880
class Map<V> extends global.Map<string, V> {

0 commit comments

Comments
 (0)