Fedoranimus Fedoranimus - 4 months ago 40
Node.js Question

Cannot extend base class with Mongoose and Typescript in NodeJS

I'm attempting to use Mongoose 4.5.4 and it's typings in NodeJS with Typescript (obviously) while utilizing the Repository Pattern.

RepositoryBase:

export class RepositoryBase<T extends mongoose.Document> implements IRead<T>, IWrite<T> {
private _model: mongoose.Model<mongoose.Document>;

constructor(schemaModel: mongoose.Model<mongoose.Document>) {
this._model = schemaModel;
}

create(item: T): mongoose.Promise<mongoose.model<T>> {
return this._model.create(item);
}

//......
//Additional CRUD methods excluded for brevity
}


UserRepository:

export class UserRepository extends RepositoryBase<IUserModel> {
constructor() {
super(UserSchema);
}
}


I have the following type error on the call to
super()
from
UserRepository


[ts]
Argument of type '<U>(name: string) => IModelConstructor<U> & EventEmitter' is not assignable to parameter of type 'IModelConstructor<Document> & EventEmitter'.
Type '<U>(name: string) => IModelConstructor<U> & EventEmitter' is not assignable to type 'IModelConstructor<Document>'.
Property 'findById' is missing in type '<U>(name: string) => IModelConstructor<U> & EventEmitter'.
import UserSchema


Does anyone know why? My creation of my model (
UserSchema
) is very simple:
let model = mongooseConnection.model<IUserModel>("Users", UserSchema.schema);


I would much appreciate a push in the right direction.

Answer

Doing a simple export const model = mongooseConnection.model<IUserModel>("Users", UserSchema.schema); was enough to solve this typing issue.