Nicolasome
Nicolasome

Reputation: 396

How to omit an attribute of a nested array type

I've defined 2 types as such:

export type Pants = {
  __typename?: 'Pants';
  id: Scalars['ObjectID'];
  price: Scalars['Int'];
  color: Scalars['String'];
};

export type Outfits = {
  __typename?: 'Outfits';
  id: Scalars['ObjectID'];
  category: Scalars['String'];
  pants: Array<Pants>;
};

Now elsewhere in my code, I want to import the Outfits type but omit the price of the nested array of Pants object.

I'm struggling to find a proper way to do so.

I've tried:

type Outfit = Omit<Outfits['pants'], 'price'>;

But that doesn't seem to work.

If I wanted to import my Outfit and omit the category I would do something like this:

type Outfit = Omit<Outfits, 'category'>;

How can I import my Outfits type but omit the price of the nested array of Pants object?

Upvotes: 2

Views: 757

Answers (1)

mahooresorkh
mahooresorkh

Reputation: 1444

You can use a mapped type to map through Outfits properties with a conditional type to check if the key is pants then omit price from its type.

type Outfit = {
  [P in keyof Outfits]: P extends "pants"
    ? Omit<Outfits[P][number], "price">[]
    : Outfits[P];
};

Upvotes: 2

Related Questions