Typescript 2.8: remove properties of one type from another

In change log 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 this, except to remove the properties of the 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; }
+5
source share
1 answer

Well, using your type Difffrom earlier (which, by the way, is the same as the type Excludethat 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; }
+4
source

Source: https://habr.com/ru/post/1695552/


All Articles