Skip to content

Commit

Permalink
Merge pull request #14430 from Automattic/vkarpov15/gh-14367
Browse files Browse the repository at this point in the history
types: consistently infer array of objects in schema as a DocumentArray
  • Loading branch information
vkarpov15 committed Mar 14, 2024
2 parents 06067de + 343593a commit b94d2fd
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 5 deletions.
34 changes: 34 additions & 0 deletions test/types/docArray.test.ts
Expand Up @@ -93,3 +93,37 @@ async function gh13424() {
const doc = new TestModel();
expectType<Types.ObjectId | undefined>(doc.subDocArray[0]._id);
}

async function gh14367() {
const UserSchema = new Schema(
{
reminders: {
type: [
{
type: { type: Schema.Types.String },
date: { type: Schema.Types.Date },
toggle: { type: Schema.Types.Boolean },
notified: { type: Schema.Types.Boolean }
}
],
default: [
{ type: 'vote', date: new Date(), toggle: false, notified: false },
{ type: 'daily', date: new Date(), toggle: false, notified: false },
{ type: 'drop', date: new Date(), toggle: false, notified: false },
{ type: 'claim', date: new Date(), toggle: false, notified: false },
{ type: 'work', date: new Date(), toggle: false, notified: false }
]
},
avatar: {
type: Schema.Types.String
}
},
{ timestamps: true }
);

type IUser = InferSchemaType<typeof UserSchema>;
expectType<string | null | undefined>({} as IUser['reminders'][0]['type']);
expectType<Date | null | undefined>({} as IUser['reminders'][0]['date']);
expectType<boolean | null | undefined>({} as IUser['reminders'][0]['toggle']);
expectType<string | null | undefined>({} as IUser['avatar']);
}
8 changes: 4 additions & 4 deletions test/types/schema.test.ts
Expand Up @@ -1059,10 +1059,10 @@ function gh12882() {
});
type tArrType = InferSchemaType<typeof arrType>;
expectType<{
fooArray: {
fooArray: Types.DocumentArray<{
type: string;
foo: number;
}[]
}>
}>({} as tArrType);
// Readonly array of strings
const rArrString = new Schema({
Expand Down Expand Up @@ -1110,10 +1110,10 @@ function gh12882() {
});
type rTArrType = InferSchemaType<typeof rArrType>;
expectType<{
fooArray: {
fooArray: Types.DocumentArray<{
type: string;
foo: number;
}[]
}>
}>({} as rTArrType);
}

Expand Down
2 changes: 1 addition & 1 deletion types/inferschematype.d.ts
Expand Up @@ -229,7 +229,7 @@ type ResolvePathType<PathValueType, Options extends SchemaTypeOptions<PathValueT
ObtainDocumentPathType<Item, TypeKey>[] :
// If the type key isn't callable, then this is an array of objects, in which case
// we need to call ObtainDocumentType to correctly infer its type.
ObtainDocumentType<Item, any, { typeKey: TypeKey }>[] :
Types.DocumentArray<ObtainDocumentType<Item, any, { typeKey: TypeKey }>> :
IsSchemaTypeFromBuiltinClass<Item> extends true ?
ObtainDocumentPathType<Item, TypeKey>[] :
IsItRecordAndNotAny<Item> extends true ?
Expand Down

0 comments on commit b94d2fd

Please sign in to comment.