mongoose
mongoose copied to clipboard
Allow type hints when inferring schema type
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!
How does __typehint work? Is that something that TypeScript supports?
@vkarpov15 see https://github.com/Automattic/mongoose/pull/14008
This was fixed with #14008