[英]TypeScript: Map union type to another union type
Is it possible to map a union type to another union type in TypeScript? 是否可以在TypeScript中将联合类型映射到另一个联合类型?
What I'd Like to be able to do 我希望能做什么
eg Given a union type A: 例如给定一个联合类型A:
type A = 'one' | 'two' | 'three';
I'd like to be able to map it to union type B: 我希望能够将它映射到联合类型B:
type B = { type: 'one' } | { type: 'two'} | { type: 'three' };
What I have tried 我试过了什么
type B = { type: A };
But this results in: 但这会导致:
type B = { type: 'one' | 'two' | 'three' };
which is not quite what I want. 这不是我想要的。
You can use conditional type for distributing over the members of the union type (conditional type always takes only one branch and is used only for its distributive property, I learned this method from this answer ) 您可以使用条件类型来分配联合类型的成员 (条件类型总是只占用一个分支,仅用于其分配属性,我从这个答案中学到了这个方法)
type A = 'one' | 'two' | 'three';
type Distribute<U> = U extends any ? {type: U} : never;
type B = Distribute<A>;
/*
type B = {
type: "one";
} | {
type: "two";
} | {
type: "three";
}
*/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.