Skip to content

Commit

Permalink
fix(types): avoid treating | undefined types as any in `Require_i…
Browse files Browse the repository at this point in the history
…d` to better support `_id: String` with auto-typed schemas

Fix #12070
  • Loading branch information
vkarpov15 committed Jul 16, 2022
1 parent 86f66b0 commit 250b01b
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
19 changes: 18 additions & 1 deletion test/types/models.test.ts
@@ -1,5 +1,14 @@
import { ObjectId } from 'bson';
import { Schema, Document, Model, connection, model, Types, UpdateQuery, CallbackError } from 'mongoose';
import {
Schema,
Document,
Model,
connection,
model,
Types,
UpdateQuery,
CallbackError
} from 'mongoose';
import { expectAssignable, expectError, expectType } from 'tsd';
import { AutoTypedSchemaType, autoTypedSchema } from './schema.test';
import { UpdateOneModel } from 'mongodb';
Expand Down Expand Up @@ -328,3 +337,11 @@ function gh12100() {
Model.syncIndexes({ continueOnError: true, noResponse: true });
Model.syncIndexes({ continueOnError: false, noResponse: true });
}

(function gh12070() {
const schema_with_string_id = new Schema({ _id: String, nickname: String });
const TestModel = model('test', schema_with_string_id);
const obj = new TestModel();

expectType<string>(obj._id);
})();
6 changes: 2 additions & 4 deletions types/index.d.ts
Expand Up @@ -109,9 +109,7 @@ declare module 'mongoose' {
}

export type Require_id<T> = T extends { _id?: infer U }
? U extends any
? (T & { _id: Types.ObjectId })
: T & Required<{ _id: U }>
? IfAny<U, T & { _id: Types.ObjectId }, T & Required<{ _id: U }>>
: T & { _id: Types.ObjectId };

export type RequireOnlyTypedId<T> = T extends { _id?: infer U; }
Expand Down Expand Up @@ -539,7 +537,7 @@ declare module 'mongoose' {
export type SchemaDefinitionType<T> = T extends Document ? Omit<T, Exclude<keyof Document, '_id' | 'id' | '__v'>> : T;

// Helpers to simplify checks
type IfAny<IFTYPE, THENTYPE> = 0 extends (1 & IFTYPE) ? THENTYPE : IFTYPE;
type IfAny<IFTYPE, THENTYPE, ELSETYPE = IFTYPE> = 0 extends (1 & IFTYPE) ? THENTYPE : ELSETYPE;
type IfUnknown<IFTYPE, THENTYPE> = unknown extends IFTYPE ? THENTYPE : IFTYPE;

// tests for these two types are located in test/types/lean.test.ts
Expand Down

0 comments on commit 250b01b

Please sign in to comment.