我有一个联合类型,如下所示:
export type TileType =
| ProductTileType
| CustomTileType
| DealTileType
| LoadingTileType
有一个需要能够接受 ProductTileType | CustomTileType | DealTileType
类型的属性的 React 组件。因此,我使用类型 Exclude<TileType, LoadingTileType>
声明了该属性,以防止在此处使用该类型。唯一的问题是 ProductTileType
的声明如下:
export interface ProductTileType extends LoadingTileType { ... }
当我排除
LoadingTileType
时,TS 还想要排除任何继承它的类型。我如何避免排除我想要排除的类型的扩展?是否还有其他我不知道的实用类型?
编辑:
type MyType = Exclude<TileType, LoadingTileType> | ProductTileType
将是解决手头问题的快速解决方法(在这种情况下,ProductTileType 是唯一继承 LoadingTileType 的类型)。但是在未来可能会有其他类型扩展 LoadingTileType
。有更好的处理方式吗?
type MyType = Exclude<TileType, LoadingTileType> | ProductTileType;
- Andrew AllisonLoadingTileType
,你还需要在这里添加新成员。但如果它能解决你的问题,那么请随意回答你自己的问题。 - zenlyLoadingTileType
作为TileType
是否有意义呢?caTS的回答在技术层面上是可行的,但如果LoadingTileType
是某种模板而独立存在没有意义(就像他们示例中的soda
),也许你应该将其删除。例如,假设caTS想要添加一种柠檬水品牌,那么在Drinks
中保留Lemonade
仍然有意义吗?也许应该包含MyBrandLemonade
和一个新的衍生品——HomeMadeLemonade
。这样,你就有了2种特定类型的Lemonade
在Drinks
中,而没有通用的。当需求改变时,领域模型也会跟着改变。 - geoffrey