Home > Software engineering >  Attempting to use the mongoose "findOne" build-in method in a generic function
Attempting to use the mongoose "findOne" build-in method in a generic function

Time:08-30

I have a typescript generic function as following:

function foo<T>(model:T): Promise<Response>{
  return model.findOne(email)
}

to call the function I do the following:

const result = await foo<'IUserModel>(User)'>
(* for those who are confused about the ' ', please ignore them *)

when I do this, I receive the following error which is:

*** Property 'findOne does not exist' on type 'T' ***

I read the mongoose documentation about the Model object but this did not help me.

Which interface or type or alternative solution is available to get rid of this typescript error?

Thank you in advance!

CodePudding user response:

Using a generic function without a constraint (extends) in the parameter tells TypeScript that model can be anything. So you could use a number, for example, and a number doesn't have the .findOne() function:

function foo<T>(model: T): Promise<Response> {
  return model.findOne() // error
}

foo(10) // no error

Using extends tells TypeScript that the model must have the Model properties, so it will always have the findOne() function:

import { Model } from 'mongoose';

function foo<T extends Model>(model: T): Promise<Response> {
  return model.findOne() // no error
}

foo(10) // error, it must be a Model

CodePudding user response:

@Lucas Surdi Franco had opened a way of solution for me.

to resolve my problem I had to extend T with Model

code solution:

import { Model } from 'mongoose';

function foo<T extends Model<T>>(model: T): Promise<Response> {
  return model.findOne()

If there is a nicer solution for this. solution, please provide it so I can learn.

  • Related