TypeScript: Map union type to another union type

筅森魡賤 提交于 2020-07-18 10:39:13

问题


Is it possible to map a union type to another union type in TypeScript?

What I'd Like to be able to do

e.g. Given a union type A:

type A = 'one' | 'two' | 'three';

I'd like to be able to map it to union type 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.


回答1:


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";
}
*/


来源:https://stackoverflow.com/questions/51691235/typescript-map-union-type-to-another-union-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!