Blog
JavaScript

Union and Intersection Types in TypeScript

Combine and extend types for flexible data modeling

Catalog

Click on this table of contents to jump to the corresponding section

To Transform union type to intersection type we have different approaches. In this article, we are going to learn how to Transform union type to intersection type.

Union Type

  • A union type in TypeScript allows a variable to have one of several types. It is represented using the | operator.
  • Example: type Animal = "Dog" | "Cat" | "Bird";
  • In this example, a variable of type Animal can have the value "Dog", "Cat", or "Bird".

Intersection Type

  • An intersection type combines multiple types into a single type, representing the combination of all types. It is represented using the & operator.
  • Example: type Person = { name: string } & { age: number };
  • In this example, a variable of type Person must have both a name property of type string and an age property of type number.

Using Distributive Conditional Types

Conditional types can be used in a distributive manner to distribute over a union of types, effectively creating an intersection type.

Example: In this example, the UnionToIntersection type uses distributive conditional types to transform a union type into an intersection type. The distributive conditional type operates over each member of the union individually, and the resulting type is the intersection of all the members.

typescript

Output:

Using Conditional Template Literal Types

Conditional template literal types provide a versatile mechanism for manipulating and transforming types in TypeScript. By combining conditional types with template literal types, we can create an elegant solution to convert union types into intersection types.

Example: In this example, we define a type UnionToIntersection that takes a union type U and recursively distributes over each member of the union. The UnionToIntersection type leverages conditional template literal types to iteratively build an intersection type by concatenating individual members of the union.

typescript

Output:

avatar

0 Comments

No comments

Leave a Reply

avatar

Recent Post

Related Topics

    Feeds

      Don't miss what's next 👋

      Enjoyed this content? Leave your email to get notified when we publish new insights, tutorials, and updates — no spam, ever.