InferSchemaType: Improve type safety by inferring {required: boolean}
as a required field instead of optional
#12782
Labels
enhancement
This issue is a user-facing general improvement that doesn't fix a bug or add a new feature
new feature
This change adds new functionality, like a new method or class
Prerequisites
🚀 Feature Proposal
If I write the following code:
SchemaType
will think thattest
is an optional string. This is because TypeScript infers the type ofdefinition
as{ test: { type: StringConstructor, required: boolean } }
instead of{ test: { type: StringConstructor, required: true } }
, so Mongoose can't infer whether the field is required in https://github.com/Automattic/mongoose/blob/master/types/inferschematype.d.ts#L83, and defaults to optional.The user can workaround this by writing
required: true as const
or defining schema definition inline into thenew Schema()
constructor, but if they don't realize something is wrong, they will end up with incorrectly optional types.I propose that we infer
required: boolean
as a required field for the following reasons:required
defaults tofalse
. If the user specifiedrequired
, it's usuallytrue
.Motivation
Improve type safety by defaulting ambiguity to required instead of optional.
Example
See above.
The text was updated successfully, but these errors were encountered: