1

在下面的代码中,我想根据收到的过滤器进行过滤。问题是每个过滤器都可以定义或不定义。我在 Lucid If 语句中遇到错误,因为可以未定义 filters.status 和 filters.departments。这是一个错误还是有一个不涉及告诉 Typescript 忽略错误的解决方案?

理论上,Lucid if 语句检查两个过滤器属性是否存在。

export interface ISalesFilter {
  status?: number[];
  departments?: string[];
 }

async filterSales(filters: ISalesFilter {
  const filteredSales = await FilterModel.query()
     .if(filters.status, (query) => {
         query.whereIn('statusId', filters.status);
      })
     .if(filters.department, (query) => {
         query.whereIn('departmentId', filters.departments); 
     });
  return filteredSales;;
}

以下解决方案有效,但对我来说听起来不是坏习惯:

export interface ISalesFilter {
  status?: number[];
  departments?: string[];
 }

async filterSales(filters: ISalesFilter {
  const filteredSales = await FilterModel.query()
     .if(filters.status, (query) => {
         if(filters.status){
             query.whereIn('statusId', filters.status);
         }
      })
     .if(filters.department, (query) => {
         if(filters.departments){
             query.whereIn('departmentId', filters.departments); 
         }
         
     });
  return filteredSales;;
}

告诉 Typescript 忽略该问题也可以,但再次失败,这不是解决此问题的好方法:

export interface ISalesFilter {
  status?: number[];
  departments?: string[];
 }

async filterSales(filters: ISalesFilter {
  const filteredSales = await FilterModel.query()
     .if(filters.status, (query) => {
         // @ts-ignore
         query.whereIn('statusId', filters.status);
         
      })
     .if(filters.department, (query) => {
         // @ts-ignore
         query.whereIn('departmentId', filters.departments);     
         
     });
  return filteredSales;;
}
4

0 回答 0