Skip to content

Commit

Permalink
Merge pull request #14526 from Automattic/vkarpov15/gh-14469
Browse files Browse the repository at this point in the history
types(DocumentArray): pass DocType generic to Document for correct toJSON() and toObject() return types
  • Loading branch information
vkarpov15 authored Apr 16, 2024
2 parents cc84536 + 904c436 commit 0c5ec09
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
37 changes: 36 additions & 1 deletion test/types/docArray.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Schema, model, Types, InferSchemaType } from 'mongoose';
import { Schema, model, Model, Types, InferSchemaType } from 'mongoose';
import { expectError, expectType } from 'tsd';

async function gh10293() {
Expand Down Expand Up @@ -127,3 +127,38 @@ async function gh14367() {
expectType<boolean | null | undefined>({} as IUser['reminders'][0]['toggle']);
expectType<string | null | undefined>({} as IUser['avatar']);
}

function gh14469() {
interface Names {
_id: Types.ObjectId;
firstName: string;
}
// Document definition
interface User {
names: Names[];
}

// TMethodsAndOverrides
type UserDocumentProps = {
names: Types.DocumentArray<Names>;
};
type UserModelType = Model<User, {}, UserDocumentProps>;

const userSchema = new Schema<User, UserModelType>(
{
names: [new Schema<Names>({ firstName: String })]
},
{ timestamps: true }
);

// Create model
const UserModel = model<User, UserModelType>('User', userSchema);

const doc = new UserModel({ names: [{ firstName: 'John' }] });

const jsonDoc = doc?.toJSON();
expectType<string>(jsonDoc?.names[0]?.firstName);

const jsonNames = doc?.names[0]?.toJSON();
expectType<string>(jsonNames?.firstName);
}
4 changes: 2 additions & 2 deletions types/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ declare module 'mongoose' {

class Decimal128 extends mongodb.Decimal128 { }

class DocumentArray<T> extends Types.Array<T extends Types.Subdocument ? T : Types.Subdocument<InferId<T>> & T> {
class DocumentArray<T> extends Types.Array<T extends Types.Subdocument ? T : Types.Subdocument<InferId<T>, any, T> & T> {
/** DocumentArray constructor */
constructor(values: AnyObject[]);

Expand All @@ -83,7 +83,7 @@ declare module 'mongoose' {
class ObjectId extends mongodb.ObjectId {
}

class Subdocument<IdType = any> extends Document<IdType> {
class Subdocument<IdType = any, TQueryHelpers = any, DocType = any> extends Document<IdType, TQueryHelpers, DocType> {
$isSingleNested: true;

/** Returns the top level document of this sub-document. */
Expand Down

0 comments on commit 0c5ec09

Please sign in to comment.