将Typescript联合类型转换为单个映射类型

时间:2019-07-11 03:59:10

标签: typescript

是否可以将联合类型转换为键为“ type”属性的映射? 例如给定联合类型为操作:

type Actions =
  | {
      type: 'campaignCreated';
      code: string;
    }
  | {
      type: 'campaignEnded';
      amount: number;
    };

我希望能够收到;

type ActionMap = {
  campaignCreated: {
    type: 'campaignCreated';
    code: string;
  };
  campaignEnded: {
    type: 'campaignEnded';
    amount: number;
  };
};

1 个答案:

答案 0 :(得分:2)

是的。

我们从根据type类型选择单个工会成员的类型开始:

type ActionSelector<T extends Actions['type'], U extends {type: Actions['type']}> = 
    U extends {type: T} ? U : never;

之所以可行,是因为当条件参数为联合时,条件类型distribute的条件超出联合类型的成员。

只需检查一下它是否可以正常工作:

type A1 = ActionSelector<'campaignCreated', Actions>

然后我们可以将其用作映射类型中的“值类型”:

type ActionMap = {[t in Actions['type']]: ActionSelector<t, Actions>};

结果是

type ActionMap = {
    campaignCreated: {
        type: "campaignCreated";
        code: string;
    };
    campaignEnded: {
        type: "campaignEnded";
        amount: number;
    };
}