在TypeScript中是否可以将联合类型映射到另一个联合类型?
我想做的事
例如给定联合类型A:
type A = 'one' | 'two' | 'three';
我希望能够将其映射到联合类型B:
type B = { type: 'one' } | { type: 'two'} | { type: 'three' };
我尝试过的事情
type B = { type: A };
但这会导致:
type B = { type: 'one' | 'two' | 'three' };
这不是我想要的。
答案 0 :(得分:7)
您可以对distributing over the members of the union type使用条件类型(条件类型始终只占用一个分支,并且仅用于其分配属性,即I 从this answer了解到了这种方法)
splitting: [17, 87, 6, 22]
splitting: [17, 87]
single: [17]
single: [87]
merged: [17, 87]
splitting: [6, 22]
single: [6]
single: [22]
merged: [6, 22]
merged: [6, 17, 22, 87]
done: [6, 17, 22, 87]