将提取的类型合并回可区分联合

问题描述 投票:0回答:1

所以我有以下类型 A,由属性“type”区分:

type A = { type: 'x', foo: boolean } | { type: 'y', bar: string }

使用这种类型我可以制作诸如

之类的对象
{
  type: 'x',
  foo: false
}

or 

{ 
  type: 'y',
  bar: "hmm"
}

我有一个类型 B,它采用来自 A 的 { type: 'x' } 判别联合,并允许额外的

baz

type B = Extract<A, { type: 'x' }> & { baz: number }

此类型 B 将允许诸如

之类的对象
{
  type: 'x'
  foo: false,
  baz: 3
}

现在,我想将这个 B 合并回另一种类型,这基本上会用 B 的定义覆盖由 'x' 区分的联合,但保持 A 中原始的 'type: y' 不变。太喜欢了


{
  type: 'x'
  foo: false,
  baz: 3
}

or 

{ 
  type: 'y',
  bar: "hmm"
}
typescript
1个回答
0
投票

您可以通过更多的类型算术来实现它。您可以首先使用

Exclude
{ type: "x" }
中减去 A,然后将新成员
B
联合回原来的成员。

type A = { type: 'x', foo: boolean } | { type: 'y', bar: string };

type B = Extract<A, { type: 'x' }> & { baz: number };

type ReplaceInDiscriminatedUnion<TUnion, TMember extends { type: unknown }> = Exclude<TUnion, Pick<TMember, 'type'> > | TMember;

type C = ReplaceInDiscriminatedUnion<A, B>;

// type C = {
//   type: 'y';
//   bar: string;
// } | B

TypeScript 游乐场

© www.soinside.com 2019 - 2024. All rights reserved.