我有一个带有know鉴别器字段的联合类型,在本例中是disc
。这些联合类型是对象文字的联合,除了鉴别器字段,它们还可以有任意字段,例如:
type Union =
| { disc: "a"; someField: string }
| { disc: "b"; some: boolean; field: number }
| { disc: "c"; foo: number }
| { disc: "d" };
我怎样才能创建一个泛型类型,它基于disc
(鉴别器)字段“删除”一些联合替代项?用TypeScript可以做到吗?
例如:
type SomeTypeTransform<Type, Keys> = ???
type UnionWithoutCAndD = SomeTypeTransform<Union, "c" | "d">
type CAndDManuallyRemoved =
| { disc: "a"; someField: string }
| { disc: "b"; some: boolean; field: number }
// I'd like UnionWithoutCAndD to be equivalent with CAndDManuallyRemoved
1条答案
按热度按时间ryevplcw1#
它实际上已经内置(如
Exclude
),但您需要 * 一点 * 更多的魔力:从文档中:
Exclude<UnionType, ExcludedMembers>
通过从
UnionType
中排除可分配给ExcludedMembers
的所有联合成员来构造类型。Playground