[英]Typescript union type to single mapped type
是否可以將聯合類型轉換為鍵為“type”屬性的映射? 例如,給定聯合類型操作:
type Actions =
| {
type: 'campaignCreated';
code: string;
}
| {
type: 'campaignEnded';
amount: number;
};
我希望能夠收到;
type ActionMap = {
campaignCreated: {
type: 'campaignCreated';
code: string;
};
campaignEnded: {
type: 'campaignEnded';
amount: number;
};
};
是的,這是可能的。
我們從一個類型選擇基礎上的一個單一的工會成員type
類型:
type ActionSelector<T extends Actions['type'], U extends {type: Actions['type']}> =
U extends {type: T} ? U : never;
它起作用是因為當條件參數是聯合時,條件類型將條件分布在聯合類型的成員上。
只需檢查它是否按預期工作:
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;
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.