Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript 2.8: Remove properties in one type from another

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; }
like image 658
Rico Kahler Avatar asked Mar 29 '18 20:03

Rico Kahler


People also ask

How do you omit a property in TypeScript?

Use the Omit utility type to exclude a property from a type, e.g. type WithoutCountry = Omit<Person, 'country'> . The Omit utility type constructs a new type by removing the specified keys from the existing type. Copied!

How do I omit multiple properties in TypeScript?

If you need to exclude multiple properties, you can pass a union of string literals to the Omit utility type.

How do I use omit TypeScript?

The TypeScript Omit utility type It will remove the fields you defined. We want to remove the id field from our user object when we want to create a user. type UserPost = Omit<User, 'id'>; const updateUser: UserPost = { firstname: 'Chris', lastname: 'Bongers', age: 32, };

What is record <> in TypeScript?

TypeScript Records are a great way to ensure consistency when trying to implement more complex types of data. They enforce key values, and allow you to create custom interfaces for the values. The TypeScript Record type was implemented in TypeScript 2.1, and takes the form Record<K, T> .


1 Answers

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; }
like image 157
CRice Avatar answered Nov 15 '22 07:11

CRice