-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
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
InferSchemaType does not infer types for virtual fields from schema #12684
Comments
As a work around, you can use the import { Schema, InferSchemaType, ObtainSchemaGeneric } from 'mongoose';
...
type User = InferSchemaType<typeof schema> & ObtainSchemaGeneric<typeof schema, 'TVirtuals'>;
const user = {} as User;
user.fullName // works |
@carlosingles, thanks for the workaround, currently I hardcoded all virtuals in an interface. @vkarpov15, I've tested the example from my initial message in 6.7.4, and the issue still persists ( If speak generally, I think it makes sense to have a way to get both interfaces (with and without virtuals). Based on first message example:
type FullUser = InferFullSchemaType<typeof schema>;
//{
// _id: ObjectId;
// id: string;
// firstName: string;
// lastName: string;
// fullName: string;
//}
function findOneUser(): Promise<FullUser> {
return UserModel.findOne().orFail().exec();
}
type PersistentUserData = InferPersistentSchemaType<typeof schema>;
//{
// firstName: string;
// lastName: string;
//}
function createUser(data: PersistentUserData): Promise<FullUser> {
return UserModel.create(data);
} Theoretically |
@Jokero I took a look and that's expected behavior. const UserModel = model('AutoTypedVirtuals', schema);
type User = ReturnType<(typeof UserModel)['hydrate']>;
const user: User = new UserModel({ firstName: 'foo' });
user.fullName; |
@Jokero are you using mongoose-lean-virtuals? |
docs(typescript): explain that virtuals inferred from schema only show up on Model, not raw document type
@vkarpov15 yes, I'm using it like this |
Prerequisites
Mongoose version
6.7.2
Node.js version
18.12.0
MongoDB server version
N/A
Typescript version (if applicable)
4.8.4
Description
InferSchemaType
does not infer types for virtual fields when schema has any. According to this PR #11908, it should work.Steps to Reproduce
Automatically Inferred Types
), create a type withInferSchemaType
and try to accessfullName
:Expected Behavior
Type
User
should containfullName: string
field, anduser.fullName
shouldn't fail TS compilation.The text was updated successfully, but these errors were encountered: