【问题标题】:Typescript 2.8: Remove properties in one type from anotherTypescript 2.8:从另一种类型中删除一种类型的属性
【发布时间】:2018-03-29 20:16:22
【问题描述】:

在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; }

【问题讨论】:

    标签: typescript typescript2.8 conditional-types


    【解决方案1】:

    好吧,利用您之前的 Diff 类型(顺便说一下,它与现在是标准库的一部分的 Exclude 类型相同),您可以编写:

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

    【讨论】:

      猜你喜欢
      • 2021-07-02
      • 1970-01-01
      • 1970-01-01
      • 2018-11-23
      • 1970-01-01
      • 2022-01-10
      • 2022-10-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多