如何为打字稿泛型指定“ this”

时间:2020-07-29 08:54:48

标签: typescript sequelize-typescript

我正在尝试创建一个实用程序功能,以自动为提供给它的模型生成分页,如下所示:

import { Model } from 'sequelize-typescript';

async function getPagination<T extends typeof Model>(model: T) {
  const page = 1;
  const limit = 10;
  const data = await model.findAndCountAll({
    limit,
    offset: (page - 1) * limit,
  });

  // Create the pagination object
  const pagination = {}; // some meaningful object

  return {
      data,
      pagination
  };
}

但是打字稿给我这个错误:

The 'this' context of type 'T' is not assignable to method's 'this' of type 'ModelStatic<Model<unknown, unknown>>'. Type 'typeof Model' is not assignable to type 'ModelStatic<Model<unknown, unknown>>'. Cannot assign an abstract constructor type to a non-abstract constructor type.

以及通过以下方式定义我的模型:

import { Table, Column, PrimaryKey, AutoIncrement, Model } from 'sequelize-typescript'

@Table
class CustomModel extends Model implements CustomModel {

  @PrimaryKey
  @AutoIncrement
  @Column
  id!: number;

}

1 个答案:

答案 0 :(得分:0)

我终于开始工作了, 实际上,我不必传递泛型本身,而必须传递泛型,后者将模型扩展到了ModelCtor,我想这就是在续集内部完成工作的方式。

async function getPagination<T extends Model>(model: ModelCtor<T>)