如何在TypeScript中省略嵌套数组类型的属性
解决方案
要实现导入Outfits类型并省略嵌套Pants数组中的price属性,你需要先创建剔除了price的Pants子类型,再重新构造Outfits类型并替换其中的pants字段。
方法1:分步定义
// 先创建去掉price属性的Pants子类型 type PantsWithoutPrice = Omit<Pants, 'price'>; // 重新构造Outfits类型,替换pants字段的类型 type Outfit = Omit<Outfits, 'pants'> & { pants: Array<PantsWithoutPrice>; };
方法2:合并为单行写法
如果不想单独定义子类型,也可以直接合并成一行:
type Outfit = Omit<Outfits, 'pants'> & { pants: Array<Omit<Pants, 'price'>>; };
为什么你的原有写法不生效?
你之前写的Omit<Outfits['pants'], 'price'>是对数组类型执行Omit操作,但数组本身并没有price属性,所以这个操作不会产生任何实际效果,自然无法剔除嵌套对象里的属性。
内容的提问来源于stack exchange,提问作者Nicolasome
相关产品推荐
相关产品推荐

