Skip to content
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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow type hints when inferring schema type #14002

Open
2 tasks done
JavaScriptBach opened this issue Oct 24, 2023 · 2 comments
Open
2 tasks done

Allow type hints when inferring schema type #14002

JavaScriptBach opened this issue Oct 24, 2023 · 2 comments
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

Comments

@JavaScriptBach
Copy link
Contributor

JavaScriptBach commented Oct 24, 2023

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

馃殌 Feature Proposal

Allow the user to specify type hints for individual schema fields, which are then respected by InferSchemaType.

Motivation

This makes Mongoose more useful in strongly typed codebases. For example, the codebase I work in has separate types for UserId and TeamId, even though both are strings at runtime. We use branded types to ensure that e.g. if a developer passes in a team ID when they should pass in a user ID, their error will be discovered at type-checking time instead of at runtime.

Example

Due to the way InferSchemaType is implemented, I can't think of a way to keep this type-only, but would you consider something like:

type UserId = BrandString<"UserId">;
const exampleUserId: UserId = "example";

const schema = new Schema({
  userId: { type: String, required: true, __typehint: exampleUserId }
});

type schemaT = InferSchemaType<typeof schema>; // { userId: UserId }

Happy to write a PR for this, if you're okay with the approach. Thanks!

@JavaScriptBach JavaScriptBach added 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 labels Oct 24, 2023
@vkarpov15
Copy link
Collaborator

How does __typehint work? Is that something that TypeScript supports?

@JavaScriptBach
Copy link
Contributor Author

@vkarpov15 see #14008

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
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
Projects
None yet
Development

No branches or pull requests

2 participants