From 250b01b0aea91d6c2bb6560b2824adc4bc648683 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Sat, 16 Jul 2022 16:14:11 -0400 Subject: [PATCH] fix(types): avoid treating `| undefined` types as `any` in `Require_id` to better support `_id: String` with auto-typed schemas Fix #12070 --- test/types/models.test.ts | 19 ++++++++++++++++++- types/index.d.ts | 6 ++---- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/test/types/models.test.ts b/test/types/models.test.ts index 5d8e33bd1d2..8d022594753 100644 --- a/test/types/models.test.ts +++ b/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'; @@ -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(obj._id); +})(); diff --git a/types/index.d.ts b/types/index.d.ts index 00252c43dd2..8b7a63bbc41 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -109,9 +109,7 @@ declare module 'mongoose' { } export type Require_id = T extends { _id?: infer U } - ? U extends any - ? (T & { _id: Types.ObjectId }) - : T & Required<{ _id: U }> + ? IfAny> : T & { _id: Types.ObjectId }; export type RequireOnlyTypedId = T extends { _id?: infer U; } @@ -539,7 +537,7 @@ declare module 'mongoose' { export type SchemaDefinitionType = T extends Document ? Omit> : T; // Helpers to simplify checks - type IfAny = 0 extends (1 & IFTYPE) ? THENTYPE : IFTYPE; + type IfAny = 0 extends (1 & IFTYPE) ? THENTYPE : ELSETYPE; type IfUnknown = unknown extends IFTYPE ? THENTYPE : IFTYPE; // tests for these two types are located in test/types/lean.test.ts