【问题标题】:Extract Record Key Types into Union Type将记录键类型提取为联合类型
【发布时间】:2023-03-17 09:25:01
【问题描述】:

给定:

interface ActionA {
  type: 'AAAA';
  stuff: string[];
}

interface ActionB {
  type: 'BBBB';
  otherStuff: string[];
}

有没有类似的东西:

type ActionTypes = ExtractToUnion<ActionA | ActionB, "type">;

构造一个类型:

type ActionTypes = 'AAAA' | 'BBBB';

【问题讨论】:

    标签: javascript typescript types extract union


    【解决方案1】:

    您可以使用index access type 查找联合的type 属性:

    type ActionTypes = (ActionA | ActionB)["type"]; // "AAAA" | "BBBB"
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-22
      • 2021-12-30
      • 2019-03-27
      • 1970-01-01
      • 2022-08-10
      • 2021-12-02
      • 2018-10-26
      相关资源
      最近更新 更多