代码之家  ›  专栏  ›  技术社区  ›  bingles

TypeScript:将联合类型映射到另一个联合类型

  •  4
  • bingles  · 技术社区  · 6 年前

    是否可以在TypeScript中将一个union类型映射到另一个union类型?

    我想做什么

    例如,给定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' };
    

    这不是我想要的。

    1 回复  |  直到 6 年前
        1
  •  12
  •   artem    6 年前

    您可以使用条件类型 distributing over the members of the union type (条件类型总是只接受一个分支,并且只用于其分配属性,I 从中学到这个方法 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";
    }
    */