Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
How to Transform Union Type to Tuple Type in TypeScript ?
Next article icon

Union Type to Intersection Type in TypeScript

Last Updated : 10 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Below are the approaches used to Transform union type to intersection type:

Table of Content

  • Using Distributive Conditional Types
  • Using Conditional Template Literal Types

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.

JavaScript
type UnionToIntersection<U> = (     U extends any ? (k: U) => void : never ) extends (k: infer I) => void     ? I     : never;  // Example usage type UnionType = { a: number } | { b: string } | { c: boolean };  type IntersectionType = UnionToIntersection<UnionType>;  // Example object of IntersectionType const myObject: IntersectionType = {     a: 42,     b: "hello",     c: true };  console.log(myObject); 

Output:

"a": 42,  
"b": "hello",
"c": true

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.

JavaScript
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (     (k: infer I) => void) ? I : never;  // Example usage type UnionType = { a: number } | { b: string } | { c: boolean };  type IntersectionType = UnionToIntersection<UnionType>;   const myObject: IntersectionType = {     a: 22,     b: "GFG",     c: true };  console.log(myObject); 

Output:

{
"a": 22,
"b": "GFG",
"c": true
}

Next Article
How to Transform Union Type to Tuple Type in TypeScript ?

A

amanv09
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • TypeScript

Similar Reads

  • TypeScript Object Intersection Types
    In TypeScript, Object Intersection Types are a way to create new types by combining multiple types into a single type. This is done using the & (ampersand) operator. Intersection types allow you to express that an object must have all the properties and methods of each type in the intersection.
    3 min read
  • How to Return a Union Type in TypeScript ?
    In TypeScript, a union type is a powerful way to express a variable that can be one of several types. Union types are used when a function or variable is expected to support multiple types of input. Union types are defined using the pipe (|) symbol between two or more types. This indicates that a va
    4 min read
  • What are intersection types in Typescript ?
    In Typescript, Although intersection and union types are similar, they are employed in completely different ways. An intersection type is a type that merges several kinds into one. This allows you to combine many types to create a single type with all of the properties that you require. An object of
    3 min read
  • How to Transform Union Type to Tuple Type in TypeScript ?
    In TypeScript, conversion from union type to tuple type consists of mapping each type in the union to a position in the tuple. This process consists of using mapped types or conditional types to perform the transformation. The below methods can be implemented to accomplish this task. Table of Conten
    3 min read
  • TypeScript Extract<Type, Union> Utility Type
    In this article, we are going to learn about Extract<Type, Union> utility type in TypeScript, TypeScript is a strongly typed programming language that builds on JavaScript, giving you better tools at any scale. Extract<Type, Union> utility type is used to extract a subset of types from a
    4 min read
  • TypeScript Defining a Union Type
    In this article, we are going to learn about Defining a Union Type in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. In TypeScript, a union type allows a variable to have one of several possible types. You can define a union type by using
    3 min read
  • TypeScript Creating Types from Utility Type
    TypeScript Creating Types from Utility Type increases the code readability and ease of use when using any complex operations and values, there are different ways to do the type creation with the existing ones. TypeScript Creating Types from Utility Type:Generics: It basically allows us to declare th
    3 min read
  • TypeScript InstanceType<Type> Utility Type
    In this article, we are going to learn about InstanceType<Type> Utility Type in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. In TypeScript, the InstanceType<Type> utility type is used to extract the instance type of a constr
    3 min read
  • TypeScript Object Interfaces vs. Intersections
    TypeScript offers several features when it comes to defining complex data structures. In TypeScript, Object Interface and Intersections are two different features that serve different purposes when it comes to defining complex data structures. Object InterfacesObject Interfaces are used to define th
    3 min read
  • TypeScript ReturnType <Type> Utility Type
    The ReturnType<Type> utility type in TypeScript extracts and infers the return type of a given function type. It enhances type safety and reusability by allowing developers to dynamically determine the type of values returned by functions without manually specifying them. Syntaxtype ResultType
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences