【问题标题】:Typescript: Transform a union of objects to a plain union打字稿:将对象的联合转换为普通的联合
【发布时间】:2020-12-22 15:38:28
【问题描述】:

如何将对象的联合转换为具有对象值的普通联合。一个例子:

type Foo = {};
type Bar = {};
type Baz = {};
type Qux = {};

type Input = {
  foo: Foo,
  bar: Bar,
} | {
  bar: Bar,
  baz: Baz,
} | {
  qux: Qux,
};

type Expected = Foo | Bar | Baz | Qux;

注意联合对象的键可能相交(例如bar)。希望解决方案能帮助我解开嵌套类型。

TS Playground.

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    您想获取类似a ValueOf<T> type(即T[keyof T])之类的东西,并将其分发T 的联合成员中,例如,如果T 是@ 987654328@,那么Transform<T> 就是A[keyof A] | B[keyof B] | C[keyof C]。您可以使用 distributive conditional type 来获得该行为:

    type Transform<T> = T extends any ? T[keyof T] : never;
    

    让我们测试一下:

    type Output = Transform<Input>
    // type Output = Foo | Bar | Baz | Qux
    

    看起来不错。

    Playground link to code

    【讨论】:

      猜你喜欢
      • 2020-10-16
      • 1970-01-01
      • 2019-07-23
      • 2019-10-25
      • 2022-01-04
      • 2021-07-03
      • 1970-01-01
      • 1970-01-01
      • 2018-12-06
      相关资源
      最近更新 更多