-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Description
Prerequisites
- I have written a descriptive issue title
- I have searched existing issues to ensure the feature has not already been requested
🚀 Feature Proposal
If I write the following code:
const definition = { test: { type: String, required: true } };
const schema = new Schema(definition);
type SchemaType = InferSchemaType<typeof schema>;
SchemaType
will think that test
is an optional string. This is because TypeScript infers the type of definition
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 the new 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
.- It's better that we type an optional field as required (makes types unnecessarily strict, but won't break) instead of vice versa (incorrectly allows optional fields which will break at runtime).
Motivation
Improve type safety by defaulting ambiguity to required instead of optional.
Example
See above.