Typegoose - how to use classes as type parameter

133 views Asked by At

I'm new to typegoose (but a long time mongoose user) and I can't figure out how to use typegoose classes as parameter type in my function. Typegoose model is working fine, but how can I use the class, not the model? (see example below)

import { prop, getModelForClass } from '@typegoose/typegoose';

class Auth {
  @prop({ required: true })
  public groupName!: string;

  @prop({ type: () => [String] })
  public rights?: string[];
}
    
export const AuthModel = getModelForClass(Auth);

// example {groupName: editors, rights:['canEditPost', 'canWriteNewPost', 'canDeletePost']}

// here I want to use Auth as parameter in my function checkRights
const checkRights = (authToCheck: Auth) => {
  const authGroup = AuthModel.findOne(groupName: authToCheck.groupName)
  const allRightsOk = authToCheck.rights.every(el => authGroup.rights.includes(el));
  return allRightsOk;
}

how can I have type checking and code completion working for authToCheck?

1

There are 1 answers

0
mochsner On

I had a similar issue in trying to assign return from MyModel.findById() to type of MyClass. It worked for some of my models, but one model just didn't let me, returning below error

`Error:(229, 9) TS2322: Type 'Document<unknown, BeAnObject, MyClass> & Omit<MyClass & Required<{ _id: ObjectId; }>, "typegooseName"> & IObjectWithTypegooseFunction' is not assignable to type 'MyClass'.`

Anyhow, solution wound up being: DocumentType<MyClass> instead of just : MyClass. Notably, this doesn't seem to work when chaining .exec() on Mongoose 8.

May have had to do with the mongoose functions or nested sub-docs on this model that caused issues. Found via https://github.com/typegoose/typegoose/issues/862