Typescript 2.8: Remove properties in one type from another
Asked Answered
C

1

5

In the changelog of 2.8, they have this example for conditional types:

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"

I want to do that except remove the properties of an object. How can I achieve the following:

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; }
Campanula answered 29/3, 2018 at 20:16 Comment(0)
D
6

Well, leveraging your Diff type from earlier (which by the way is the same as the Exclude type which is now part of the standard library), you can write:

type ObjectDiff<T, U> = Pick<T, Diff<keyof T, keyof U>>;
type AWithoutStuff = ObjectDiff<A, Stuff>; // inferred as { one: string; two: number; }
Dictionary answered 29/3, 2018 at 20:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.