feat: Enhance type safety for MongoDB filter conditions by introducing helper types for $in and $nin values
This commit is contained in:
		| @@ -151,6 +151,12 @@ export function index(options?: IIndexOptions) { | |||||||
|   }; |   }; | ||||||
| } | } | ||||||
|  |  | ||||||
|  | // Helper type to extract element type from arrays or return T itself | ||||||
|  | type ElementOf<T> = T extends ReadonlyArray<infer U> ? U : T; | ||||||
|  |  | ||||||
|  | // Type for $in/$nin values - arrays of the element type | ||||||
|  | type InValues<T> = ReadonlyArray<ElementOf<T>>; | ||||||
|  |  | ||||||
| // Type that allows MongoDB operators on leaf values while maintaining nested type safety | // Type that allows MongoDB operators on leaf values while maintaining nested type safety | ||||||
| export type MongoFilterCondition<T> = T | { | export type MongoFilterCondition<T> = T | { | ||||||
|   $eq?: T; |   $eq?: T; | ||||||
| @@ -159,15 +165,15 @@ export type MongoFilterCondition<T> = T | { | |||||||
|   $gte?: T; |   $gte?: T; | ||||||
|   $lt?: T; |   $lt?: T; | ||||||
|   $lte?: T; |   $lte?: T; | ||||||
|   $in?: T extends (infer U)[] ? U[] | U : T[]; |   $in?: InValues<T>; | ||||||
|   $nin?: T extends (infer U)[] ? U[] | U : T[]; |   $nin?: InValues<T>; | ||||||
|   $exists?: boolean; |   $exists?: boolean; | ||||||
|   $type?: string | number; |   $type?: string | number; | ||||||
|   $regex?: string | RegExp; |   $regex?: string | RegExp; | ||||||
|   $options?: string; |   $options?: string; | ||||||
|   $all?: T extends (infer U)[] ? U[] : never; |   $all?: T extends ReadonlyArray<infer U> ? ReadonlyArray<U> : never; | ||||||
|   $elemMatch?: T extends (infer U)[] ? MongoFilter<U> : never; |   $elemMatch?: T extends ReadonlyArray<infer U> ? MongoFilter<U> : never; | ||||||
|   $size?: T extends any[] ? number : never; |   $size?: T extends ReadonlyArray<any> ? number : never; | ||||||
|   $not?: MongoFilterCondition<T>; |   $not?: MongoFilterCondition<T>; | ||||||
| }; | }; | ||||||
|  |  | ||||||
|   | |||||||
		Reference in New Issue
	
	Block a user