typescript 如何省略嵌套数组类型的属性

3hvapo4f  于 2022-11-18  发布在  TypeScript
关注(0)|答案(1)|浏览(108)

我定义了两种类型:

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>;
};

现在,在代码的其他地方,我想导入Outfits类型,但忽略Pants对象的嵌套数组的price
我正在努力寻找一个合适的方法来这样做。
我试过了:

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

但这似乎行不通。
如果我想导入我的Outfit并忽略category,我会这样做:

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

如何导入Outfits类型,但忽略Pants对象嵌套数组的price

ulydmbyx

ulydmbyx1#

您可以使用mapped type来MapOutfits属性,使用conditional type来检查键是否为pants,然后从其类型中忽略price

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

相关问题