代码之家  ›  专栏  ›  技术社区  ›  Rico Kahler

Typescript 2.8:从一种类型中删除另一种类型中的属性

  •  5
  • Rico Kahler  · 技术社区  · 8 年前

    在 changelog of 2.8 ,条件类型的示例如下:

    type Diff<T, U> = T extends U ? never : T;  // Remove types from T that are assignable to U
    type T30 = Diff<"a" | "b" | "c" | "d", "a" | "c" | "f">;  // "b" | "d"
    

    我只想删除对象的属性。如何实现以下目标:

    type ObjectDiff<T, U> = /* ...pls help... */;
    
    type A = { one: string; two: number; three: Date; };
    type Stuff = { three: Date; };
    
    type AWithoutStuff = ObjectDiff<A, Stuff>; // { one: string; two: number; }
    
    1 回复  |  直到 7 年前
        1
  •  6
  •   CRice    8 年前

    好吧,利用你的 Diff 键入早期版本(顺便说一下,与 Exclude 类型(现在是标准库的一部分),您可以编写:

    type ObjectDiff<T, U> = Pick<T, Diff<keyof T, keyof U>>;
    type AWithoutStuff = ObjectDiff<A, Stuff>; // inferred as { one: string; two: number; }
    
    推荐文章