My goal is to enhance the typing capabilities of the MongoDB query system.
Consider this object
interface Person { name: string; age: number }
I aim to construct a query object that permits the use of $gt
exclusively on the age
field, as it is a numerical value and not applicable to the name
field.
An example would be:
{ age: { $gt: 21 } }
, which is valid for querying based on age but not{ name: { $gt: 21 } }
To achieve this, I propose the following structure:
type MongoConditions<T> = { [P in keyof T]?: T[P] | { $gt: number }; // This condition should only apply if T[P] is a number };
For instance, the following code snippet should be allowed:
const condition: MongoConditions<Person> = { age: { $gt: 21 }, name: 'foo' }
However, the compilation should fail for the following scenario:
const condition3: MongoConditions<Person> = { age: 21, name: { $gt: 21 } }