Search code examples
typescript

How to combine two union types?


type A = 1 | 2 | 3
type B = 4 | 5 & A
type C = A & 4 | 5
type D = A & (4 | 5)
type E = (4 | 5) & A

type X = 1 | 2 | 3 | 4 | 5

typeX is the result I expected.

TypeB and TypeC are the attempts I made, but they all failed.

What is the correct approach?


Solution

  • If you have the union

    type A = 1 | 2 | 3
    

    and want a union with more members like

    type B = 1 | 2 | 3 | 4 | 5
    

    You can replace 1 | 2 | 3 by A and get

    type B = A | 4 | 5
    

    That is, you want a union of unions. There's no reason to use the intersection operator unless you're trying to remove members.

    Playground link to code