Skip to content

Schema.create() for TypeScript type inference #15482

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: 9.0
Choose a base branch
from

Conversation

vkarpov15
Copy link
Collaborator

Summary

The key idea behind fixing #14954 and related issues is to infer the raw document type and hydrated document type directly from the schema definition, rather than attempting to infer the hydrated document type from the raw document type. The new Schema.create() function does just that.

We did some work attempting to pull this logic into new Schema() directly in 9.0...vkarpov15/gh-14954-scratch-2, but unfortunately that would require shifting around the generic params to new Schema() significantly - we would have to make TSchemaDefinition the first generic param, which would break anyone who is using new Schema<RawDoc>().

@hasezoey can you try out Schema.create() in Typegoose and see what happens?

Examples

@vkarpov15 vkarpov15 added this to the 9.0 milestone Jun 19, 2025
Copy link
Contributor

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR introduces a static Schema.create() method for clearer TypeScript type inference by directly inferring the raw and hydrated document types from the schema definition.

  • Updated test cases to reflect the inclusion of _id: Types.ObjectId in the inferred document types.
  • Added the Schema.create() method in lib/schema.js with supporting documentation.

Reviewed Changes

Copilot reviewed 3 out of 9 changed files in this pull request and generated no comments.

File Description
test/types/schema.test.ts Updated expected type to include _id property in the RawDocType inference.
test/types/inferrawdoctype.test.ts Updated expected type to include _id property in the inferred raw document type.
lib/schema.js Introduced Schema.create() with detailed JSDoc for improved TypeScript inference.
Comments suppressed due to low confidence (1)

lib/schema.js:376

  • Consider updating the documentation to explicitly mention that Schema.create() infers _id: Types.ObjectId by default, which affects the resulting document types.
 * Creates a new schema with the given definition and options. Equivalent to `new Schema(definition, options)`.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant