mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

Allow type hints when inferring schema type

Open JavaScriptBach opened this issue 2 years ago • 2 comments

Prerequisites

  • [X] I have written a descriptive issue title
  • [X] 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 avatar Oct 24 '23 23:10 JavaScriptBach

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

vkarpov15 avatar Oct 25 '23 17:10 vkarpov15

@vkarpov15 see https://github.com/Automattic/mongoose/pull/14008

JavaScriptBach avatar Oct 25 '23 22:10 JavaScriptBach

This was fixed with #14008

vkarpov15 avatar Jun 05 '24 20:06 vkarpov15