Sequelize-Typescript 类型模型

Sequelize-Typescript typeof model

我正在尝试创建一个采用 Sequelize 模型并为其创建所有基本 API 的基本 CRUD 服务,所以我是这样做的:

export class RepositoryService<T extends Model<T>> {
  constructor(protected model: typeof Model) {
  }
  public async getMany(
    query: RequestParamsParsed = {},
    options: RestfulOptions = {},
  ): Promise<T[]> {
    return this.model.findAll();
  }
}

我收到以下错误:

The 'this' context of type 'typeof Model' is not assignable to method's 'this' of type 'new () => Model<Model<any>>'.
  Cannot assign an abstract constructor type to a non-abstract constructor type.

这是因为 seqeulize-typescript 包中的这一行:

static findAll<T extends Model<T>>(this: (new () => T), options?: IFindOptions<T>): Promise<T[]>;

我对 Typescript 比较陌生,所以如果有人能告诉我 findAll 函数中 this: (new () => T) 的含义是什么,我该如何解决。

问题似乎出在这一行

constructor(protected model: typeof Model) {}

我设置的模型类型 Model 是从 sequelize-typescript 导入的,而我应该使用从 sequelize 本身导出的原始模型。

整个代码是这样的:

import { Model as OriginalModel } from 'sequelize';
import { Model } from 'sequelize-typescript';
export class RepositoryService<T extends Model<T>> {
  constructor(protected model: typeof OriginalModel) {
  }
  public async getMany(
    query: RequestParamsParsed = {},
    options: RestfulOptions = {},
  ): Promise<T[]> {
    return this.model.findAll();
  }
}

在使用 sequelize-typescript 库时也遇到了这个错误。

您可以先定义这些助手类型:

import { Model } from "sequelize-typescript";

// Type `ModelType` would basically wrap & satisfy the 'this' context of any sequelize helper methods
type Constructor<T> = new (...args: any[]) => T;
type ModelType<T extends Model<T>> = Constructor<T> & typeof Model;

然后,将其与您的代码一起使用:

export class RepositoryService<T extends Model<T>> {
  constructor(protected model: ModelType<T>) {}

  public async getMany(
    query: RequestParamsParsed = {},
    options: RestfulOptions = {},
  ): Promise<T[]> {
    return this.model.findAll();
  }
}

希望对您有所帮助。

使用"sequelize-typescript": "2.1.0"你可以使用模块提供的ModelCtor例如

import { Model, ModelCtor } from 'sequelize-typescript';

export class RepositoryService<T extends Model<T>> {
  constructor(protected model: ModelCtor<T>) {}

  public async getMany(
    query: RequestParamsParsed = {}, 
    options: RestfulOptions = {}
): Promise<T[]> {
    return this.model.findAll();
  }
}

ModelCtor类型是:

export declare type Repository<M> = (new () => M) & NonAbstract<typeof Model>;

export declare type ModelCtor<M extends Model = Model> = Repository<M>;