Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Omit multiple properties in a succint way using Omit<>

In the following type definition I am using Omit two time to remove two property from B definition. I would like to know if it is possible to use only a single Omit but removing two or more properties in one shot.

export type A = Readonly<{
  x: number;
  y: number;
  j: string;
  k: string;
}>;

export type B = Omit<A, 'j'> & Omit<A, 'k'>
like image 553
Radex Avatar asked Aug 22 '19 06:08

Radex


People also ask

How do I omit multiple keys in TypeScript?

To omit multiple keys from an object, pass a union of string literals in K . In the next example, we generate a Person type off of SoccerPlayer by removing the team and careerGoals .

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!

What does Omit do in TypeScript?

TypeScript provides a number of utility types which are used to solve a particular problem that using types in Javascript creates. One very useful utility type used in TypeScript is the Omit type, which lets us customize an already existing type.


1 Answers

You just need to use a union as the second type parameter to remove all constituents in the union from the first type parameter:

export type A = Readonly<{
  x: number;
  y: number;
  j: string;
  k: string;
}>;

export type B = Omit<A, 'j' | 'k'>
// Same as
// type B = {
//     readonly x: number;
//     readonly y: number;
// }

play

like image 131
Titian Cernicova-Dragomir Avatar answered Oct 02 '22 18:10

Titian Cernicova-Dragomir