How to use Distributive Conditional Types In Typescript
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.
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
Union Type to Intersection Type in TypeScript
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 aname
property of typestring
and anage
property of typenumber
.