Skip to content

InferSchemaType: Improve type safety by inferring {required: boolean} as a required field instead of optional #12782

@JavaScriptBach

Description

@JavaScriptBach

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:

  1. required defaults to false. If the user specified required, it's usually true.
  2. 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementThis issue is a user-facing general improvement that doesn't fix a bug or add a new featurenew featureThis change adds new functionality, like a new method or class

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions