How to use Conditional Template Literal Types In Typescript
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.
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
}
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
.