代码之家  ›  专栏  ›  技术社区  ›  MikhailBeloborodov

如何在TypeScript中过滤类似对象的并集类型?

  •  1
  • MikhailBeloborodov  · 技术社区  · 2 年前

    假设我有3种类型和它们的并集类型:

    type Cat = {
      owner: string;
      color: string;
      lives: number;
    }
    
    type Dog = {
      owner: string;
      color: string;
    }
    
    type Wolf = {
      color: string;
    }
    
    type Animals = Cat | Dog | Wolf;
    

    我想要一个过滤器 AnimalsFilter<U, K> 工作方式如下:

    type FilterAnimals<U, K extends string> = ...;
    
    type WithOwner = FilterAnimals<Animals, 'owner'>;
    // WithOwner = Cat | Dog
    

    因此,在过滤此并集类型后,它将只有Cat和Dog。我怎样才能做到这一点?

    我试着绘制地图,如下所示:

    type FilterAnimals<U, K extends string> = {
        [Key in keyof U]: Key extends K? U[K] : never;
    }[keyof U];
    

    但它并没有按预期工作。我差点就要回答这个问题了吗?

    1 回复  |  直到 2 年前
        1
  •  1
  •   jcalz    2 年前

    你可以写 HasKey<T, K> 作为一个 distributive conditional type 分割 union type T 进入其成员,然后通过执行另一个条件检查 keyof 只想让那些有钥匙的成员远离 K 。像这样:

    type HasKey<T, K extends PropertyKey> =
      T extends unknown ? K extends keyof T ? T : never : never;
    
    type AnimalsWithOwner = HasKey<Animals, "owner">;
    // type AnimalsWithOwner = Cat | Dog
    

    Playground link to code

    推荐文章