Skip to content

Commit

Permalink
types(DocumentArray): pass DocType generic to Document for correct to…
Browse files Browse the repository at this point in the history
…JSON() and toObject() return types

Fix #14469
  • Loading branch information
vkarpov15 committed Apr 15, 2024
1 parent 78bbcb5 commit 904c436
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
@@ -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
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 904c436

Please sign in to comment.