简体   繁体   English

打字稿联合类型到单个映射类型

[英]Typescript union type to single mapped type

Is it possible to convert a union type to a map with the key being "type" property?是否可以将联合类型转换为键为“type”属性的映射? eg Given a union type Actions:例如,给定联合类型操作:

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

I'd like to be able to receive;我希望能够收到;

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

Yes it's possible.是的,这是可能的。

We start with a type for selecting a single union member based on the type type:我们从一个类型选择基础上的一个单一的工会成员type类型:

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

It works because conditional types distribute the condition over the members of the union type, when the condition argument is a union.它起作用是因为当条件参数是联合时,条件类型将条件分布在联合类型的成员上。

Just a check that it works as expected:只需检查它是否按预期工作:

type A1 = ActionSelector<'campaignCreated', Actions>

Then we can use it as 'value type' in a mapped type:然后我们可以将它用作映射类型中的“值类型”:

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

the result is结果是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM