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; }
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!
If you need to exclude multiple properties, you can pass a union of string literals to the Omit utility type.
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, };
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> .
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With