From 09d0d25fdc63a5f5c9a2b7c240e85db7d3730888 Mon Sep 17 00:00:00 2001 From: Kir_Antipov Date: Thu, 22 Dec 2022 16:11:15 +0000 Subject: [PATCH] Made a type that converts unions to intersections --- src/utils/types/union-to-intersection.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 src/utils/types/union-to-intersection.ts diff --git a/src/utils/types/union-to-intersection.ts b/src/utils/types/union-to-intersection.ts new file mode 100644 index 0000000..1166baa --- /dev/null +++ b/src/utils/types/union-to-intersection.ts @@ -0,0 +1,16 @@ +/** + * Converts a union type to an intersection type. + * + * This type takes advantage of TypeScript's inference and distributive conditional types. + * It starts by using a mapped type to distribute the conditional type over the union type `T`. + * For each distributed type, it creates a function type with the type parameter as its argument. + * Then, it infers the intersection type `U` by analyzing the compatibility of the function types. + * The process results in an intersection type representing the combination of all distributed types. + * + * @template T - The union type to be converted into an intersection type. + * + * @returns The intersection type created from the union type `T`. + */ +export type UnionToIntersection = ( + T extends unknown ? (x: T) => void : never +) extends (x: infer U) => void ? U : never;