用于从标记联合中删除的类型运算符

type operator for removing from a tagged union

是否可以从标记联合/可区分联合中删除特定类型文字?这样的类型怎么写?

鉴于此类型:

type MyUnion = {
  kind: "foo"
  foo: number
} | {
  kind: "bar"
  bar: string
} | {
  kind: "baz"
  baz: boolean
}

我想删除 {kind: "baz", baz: boolean} 类型文字。是否可以这样写 type RemoveTag<T, K, V>

type MyUnionWithoutBaz = RemoveTag<MyUnion, "kind", "baz">

产量:

type MyUnionWithoutBaz = {
  kind: "foo"
  foo: number
} | {
  kind: "bar"
  bar: string
}

?

您可以使用 the Exclude<T, U> utility type 从联合 T 中过滤出不可分配给另一种类型 U 的成员。因此,您的 RemoveTag 类型可以写成

type RemoveTag<T, K extends keyof T, V> =
  Exclude<T, Record<K, V>>

取决于您的用例(如果判别式 属性 是 optional 那么它就不会按原样工作)。对于您的示例,它会产生:

type MyUnionWithoutBaz = RemoveTag<MyUnion, "kind", "baz">
/* type TWithoutBaz = {
    kind: "foo";
    foo: number;
} | {
    kind: "bar";
    bar: string;
} */

随心所欲。

Playground link to code