Skip to content

Conversation

@sffc
Copy link
Contributor

@sffc sffc commented Jan 5, 2023

Summary

I sometimes use virtuals in the definition of other virtuals in my Mongoose schemas. This change allows virtuals to invoke other virtuals in TypeScript.

Examples

I have this code:

userSchema.virtual("tier").get(function() {
	// ...
	candidate = this.programModel?.tier_override;
	// ...
});

In this code, programModel is a virtual. However, compiling this code gives me an error:

src/user_model.ts:208:19 - error TS2339: Property 'programModel' does not exist on type 'Document<unknown, any, IUser> & IUser & Required<{ _id: ObjectId; }> & IUserMethods'.

208  candidate = this.programModel?.tier_override;
                      ~~~~~~~~~~~~

This PR fixes the error.

I have my virtuals defined in their own interface:

interface IUserVirtuals {
	// ...
	tier: string;
	programModel: IProgram | null | undefined;
	// ...
}

I use the following type shortcuts:

type UserModel = Mongoose.Model<IUser, {}, IUserMethods, IUserVirtuals>;
type UserSchema = Mongoose.Schema<IUser, UserModel, IUserMethods, {}, IUserVirtuals>;
type HydratedUser = Mongoose.HydratedDocument<IUser, IUserMethods, IUserVirtuals>;

The two {} are stand-ins for TQueryHelpers, which I don't currently use.

@vkarpov15 vkarpov15 added this to the 6.8.3 milestone Jan 6, 2023
Copy link
Collaborator

@vkarpov15 vkarpov15 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks

@vkarpov15 vkarpov15 merged commit fadb450 into Automattic:master Jan 6, 2023
@sffc sffc deleted the patch-1 branch January 6, 2023 19:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants