Skip to content

Commit

Permalink
Merge pull request #14510 from Automattic/vkarpov15/gh-14473
Browse files Browse the repository at this point in the history
types(query): make `FilterQuery` props resolve to `any` for generics support
  • Loading branch information
vkarpov15 authored Apr 10, 2024
2 parents e35fc63 + 3dd6edb commit 893b9d6
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 21 deletions.
24 changes: 22 additions & 2 deletions test/types/queries.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import {
FilterQuery,
UpdateQuery,
UpdateQueryKnownOnly,
ApplyBasicQueryCasting,
QuerySelector,
InferSchemaType,
ProjectionFields,
Expand Down Expand Up @@ -325,7 +324,7 @@ function gh11964() {
}

function gh14397() {
type Condition<T> = ApplyBasicQueryCasting<T> | QuerySelector<ApplyBasicQueryCasting<T>>; // redefined here because it's not exported by mongoose
type Condition<T> = T | QuerySelector<T>; // redefined here because it's not exported by mongoose

type WithId<T extends object> = T & { id: string };

Expand Down Expand Up @@ -592,3 +591,24 @@ function mongooseQueryOptions() {
populate: 'test'
});
}

function gh14473() {
class AbstractSchema {
_id: any;
createdAt: Date;
updatedAt: Date;
deletedAt: Date;

constructor() {
this._id = 4;
this.createdAt = new Date();
this.updatedAt = new Date();
this.deletedAt = new Date();
}
}

const generateExists = <D extends AbstractSchema = AbstractSchema>() => {
const query: FilterQuery<D> = { deletedAt: { $ne: null } };
const query2: FilterQuery<D> = { deletedAt: { $lt: new Date() } };
};
}
23 changes: 4 additions & 19 deletions types/query.d.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,7 @@
declare module 'mongoose' {
import mongodb = require('mongodb');

type StringQueryTypeCasting = string | RegExp;
type ObjectIdQueryTypeCasting = Types.ObjectId | string;
type UUIDQueryTypeCasting = Types.UUID | string;

type QueryTypeCasting<T> = T extends string
? StringQueryTypeCasting
: T extends Types.ObjectId
? ObjectIdQueryTypeCasting
: T extends Types.UUID
? UUIDQueryTypeCasting
: T | any;

export type ApplyBasicQueryCasting<T> = T | T[] | (T extends (infer U)[] ? QueryTypeCasting<U> : T);
export type Condition<T> = ApplyBasicQueryCasting<QueryTypeCasting<T>> | QuerySelector<ApplyBasicQueryCasting<QueryTypeCasting<T>>>;

type _FilterQuery<T> = {
[P in keyof T]?: Condition<T[P]>;
} & RootQuerySelector<T>;
export type Condition<T> = T | QuerySelector<T | any> | any;

/**
* Filter query to select the documents that match the query
Expand All @@ -27,7 +10,9 @@ declare module 'mongoose' {
* { age: { $gte: 30 } }
* ```
*/
type FilterQuery<T> = _FilterQuery<T>;
type FilterQuery<T> = {
[P in keyof T]?: Condition<T[P]>;
} & RootQuerySelector<T>;

type MongooseBaseQueryOptionKeys =
| 'context'
Expand Down

0 comments on commit 893b9d6

Please sign in to comment.