【问题标题】:Generic TypeScript type for filters过滤器的通用 TypeScript 类型
【发布时间】:2021-03-01 21:26:17
【问题描述】:

我有通用存储库接口:

type RecursivePartial<T> = {
  [P in keyof T]?:
    T[P] extends (infer U)[] ? RecursivePartial<U>[] :
    T[P] extends object ? RecursivePartial<T[P]> :
    T[P];
};

interface Repository<T> {
  all(filters?: RecursivePartial<T>): T[] | Promise<T[]>;
  find(filters: RecursivePartial<T>): T | undefined | Promise<T | undefined>;
  create(entity: T): T | Promise<T>;
  update(entity: T, fields: RecursivePartial<T>): T | Promise<T>;
}

当我想找到一个实体时

repository.find({ property: value })

工作正常。但是现在当我有从 MongoDB 查询数据的存储库时,我需要一种既支持精确过滤又支持查询的类型

repository.find({ property: { $exists: true } })

附:或许你知道如何处理Promise | T

【问题讨论】:

    标签: mongodb typescript typescript-generics


    【解决方案1】:

    您可以在T[P] 基本情况下添加一个额外的联合类型:

    type HigherFilter = {
        $exists?: boolean,
    };
    
    type RecursivePartial<T> = {
      [P in keyof T]?:
        T[P] extends (infer U)[] ? RecursivePartial<U>[] :
        T[P] extends object ? RecursivePartial<T[P]> :
        T[P] | HigherFilter; // <---- HERE
    };
    

    Playground Link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      • 2020-03-17
      • 2020-10-31
      • 1970-01-01
      • 2018-11-04
      • 2021-07-07
      相关资源
      最近更新 更多