-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
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
types: make toObject() and toJSON() not generic by default to avoid type widening #14819
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks good to me, would have to change something in typegoose as we seemingly relied on this behavior.
simplified example of what the use-case was:
interface User {
name: string;
}
const pojo: User & { _id: mongoose.Types.ObjectId; id: string } = doc.toObject({ virtuals: true, getters: true });
// Error:
// Property 'id' is missing in type 'User & { _id: ObjectId; }' but required in type '{ _id: ObjectId; id: string; }'.
(TL;DR: we needed types for the default id
virtual / getter, but it does not currently exist in mongoose yet, iirc)
link to actual typegoose source
Fix #12883
Summary
Making document methods generic by default makes TypeScript do some strange type widening where it automatically infers the generic parameter if the variable being assigned has an explicit type. This PR makes
toJSON()
andtoObject()
not generic by default.In the interest of caution, I'm targeting merging this in v8.6 because it may cause some issues for users that rely on the broken behavior.
Examples