首页 > 解决方案 > 使用不同的参数类型制作分页功能

问题描述

我是 typescript 的新手,在我的 Nodejs 应用程序中,我创建了一个中间件来对传入的对象数组进行分页。

我有时希望这个数组是 mongoose 类型Model,但我也希望它能够包含一个普通的对象数组。

到目前为止,这是我的代码:


import { Request, Response, NextFunction } from 'express';
import expressAsyncHandler from 'express-async-handler';
import { Model } from 'mongoose';

const paginate = function <M>(model: Model<M>) {
  return expressAsyncHandler(async function (
    req: Request,
    res: Response,
    next: NextFunction
  ) {
    try {

     
      const modelArray = await model.find({});
      /// ...rest of the code..

}
catch(err){
// ....
}
  });
};

我这样称呼它:

router.get('/',paginate(Category), getAllCategories);

因此,当paginate接收到一个 Category- 这是一个 Mongoose 模型时,它会将类型分配给model分页内的参数。

如果我想用不同的数据调用分页怎么办?如果你使用 {[a:1],[b:2]} 会怎样?


import { Request, Response, NextFunction } from 'express';
import expressAsyncHandler from 'express-async-handler';
import { Model } from 'mongoose';

 type IAgrs<Type> = Record<string, unknown>[] | Model<Type>;

const paginate = function <M>(model: IAgrs<M>) {
  return expressAsyncHandler(async function (
    req: Request,
    res: Response,
    next: NextFunction
  ) {
    try {
      const modelArray = await model.find({});
      /// ...rest of the code..

}
catch(err){
// ....
}
  });
};

我知道调用find({}){[a:1],[b:2]} 解决错误,但我收到的错误对我来说并不清楚,原因findArray原型上的方法,我告诉 Typescriptmodel可以是 Array 类型。

This expression is not callable. Each member of the union type '{ <S extends Record<string, unknown>>(predicate: (this: void, value: Record<string, unknown>, index: number, obj: Record<string, unknown>[]) => value is S, thisArg?: any): S | undefined; (predicate: (value: Record<...>, index: number, obj: Record<...>[]) => unknown, thisArg?: any): Record<...> | undefined; } | { ......' has signatures, but none of those signatures are compatible with each other.

我不明白为什么。有没有办法让这个函数同时接收模型类型和对象数组类型?

非常感谢。

标签: node.jstypescriptmongodbmongoose

解决方案


推荐阅读