A
A
alex4answ2020-10-17 16:19:24
typescript
alex4answ, 2020-10-17 16:19:24

How to pass a sequelize model class as a parameter?

TS swears, I tried it in different ways:

import type { Model } from 'sequelize';

const isExistsValidator = (model: typeof Model, field: string) => {
  return async (value): boolean => {
    const result = await model.findOne({ where: { [field]: value } }); // No overload matches this call.
    // ...
  };
};

import type { Model, ModelStatic } from 'sequelize';

const isExistsValidator = <M extends Model>(model: ModelStatic<M>, field: string) { 
  // ...
  const result = await model.findOne({ where: { [field]: value } });// Property 'findOne' does not exist on type
}

import type { Model } from 'sequelize';

const isExistsValidator = (model: Model, field: string) { 
  // ...
  const result = await model.findOne({ where: { [field]: value } });// Property 'findOne' is a static member of type 'Model<any, any>'

It will be used like this:
const isExistsName = isExistsValidator(UserModel, 'name');
// ...
if(await isExistsName('alex4answer')) {
  throw new Error('Name already in use');
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question