Skip to content

Commit

Permalink
fix(types): handle arrays in ApplyBasicQueryCasting correctly
Browse files Browse the repository at this point in the history
Fix #11964
  • Loading branch information
vkarpov15 committed Jun 24, 2022
1 parent e991892 commit b66cdc6
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
34 changes: 33 additions & 1 deletion test/types/queries.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,18 @@
import { HydratedDocument, Schema, model, Document, Types, Query, Model, QueryWithHelpers, PopulatedDoc, FilterQuery, UpdateQuery } from 'mongoose';
import {
HydratedDocument,
Schema,
model,
Document,
Types,
Query,
Model,
QueryWithHelpers,
PopulatedDoc,
FilterQuery,
UpdateQuery,
ApplyBasicQueryCasting,
QuerySelector
} from 'mongoose';
import { ObjectId } from 'mongodb';
import { expectError, expectType } from 'tsd';
import { autoTypedModel } from './models.test';
Expand Down Expand Up @@ -295,3 +309,21 @@ function autoTypedQuery() {
const query = AutoTypedModel.find();
expectType<typeof query>(AutoTypedModel.find().byUserName(''));
}

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

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

class Repository<T extends object> {
/* ... */

find(id: string) {
const idCondition: Condition<WithId<T>>['id'] = id; // error :(
const filter: FilterQuery<WithId<T>> = { id }; // error :(

/* ... */
}
}

}
2 changes: 1 addition & 1 deletion types/query.d.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
declare module 'mongoose' {
import mongodb = require('mongodb');

export type ApplyBasicQueryCasting<T, defaultT = T | T[] | {}> = T extends any[] ? T[0] & defaultT: defaultT;
export type ApplyBasicQueryCasting<T> = T | T[] | (T extends (infer U)[] ? U : any) | any;
type Condition<T> = ApplyBasicQueryCasting<T> | QuerySelector<ApplyBasicQueryCasting<T>>;

type _FilterQuery<T> = {
Expand Down

0 comments on commit b66cdc6

Please sign in to comment.