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’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

Merged
merged 1 commit into from
Aug 20, 2024

Conversation

vkarpov15
Copy link
Collaborator

@vkarpov15 vkarpov15 commented Aug 19, 2024

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() and toObject() 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

@vkarpov15 vkarpov15 added this to the 8.6 milestone Aug 19, 2024
Copy link
Collaborator

@hasezoey hasezoey left a 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

@hasezoey hasezoey added the typescript Types or Types-test related issue / Pull Request label Aug 20, 2024
@vkarpov15 vkarpov15 merged commit 8180a73 into 8.6 Aug 20, 2024
4 of 5 checks passed
@vkarpov15 vkarpov15 deleted the vkarpov15/gh-12883 branch August 20, 2024 15:48
hasezoey added a commit to typegoose/typegoose that referenced this pull request Aug 31, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
typescript Types or Types-test related issue / Pull Request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants