From bd8a2f67068ce40d9bba620b0aeebbaf721d605c Mon Sep 17 00:00:00 2001 From: Aleksandr Neyasov Date: Wed, 9 Apr 2025 16:58:01 +0400 Subject: [PATCH] Replace unionToTuple with works one --- src/data/stages.derived.ts | 6 ++-- src/types/unionToTuple.ts | 63 ++++++++++++++++++++------------------ 2 files changed, 36 insertions(+), 33 deletions(-) diff --git a/src/data/stages.derived.ts b/src/data/stages.derived.ts index 589e451..15a7f5d 100644 --- a/src/data/stages.derived.ts +++ b/src/data/stages.derived.ts @@ -3,17 +3,17 @@ // the manually entered values. import { NeverForEmpty } from "../types/NeverForEmpty"; -import { TuplifyUnionAnyOrder } from "../types/unionToTuple"; +import { TuplifyUnion } from "../types/unionToTuple"; import { bridgedChains, stages } from "./stages"; export type Stages = typeof stages; export type StageId = keyof Stages; -export type StageIdsOrder = TuplifyUnionAnyOrder; +export type StageIdsOrder = TuplifyUnion; export type BridgedChains = typeof bridgedChains; export type BridgedChainId = NeverForEmpty; -export type BridgedChainIdsOrder = TuplifyUnionAnyOrder; +export type BridgedChainIdsOrder = TuplifyUnion; diff --git a/src/types/unionToTuple.ts b/src/types/unionToTuple.ts index 7a5be3b..5870d05 100644 --- a/src/types/unionToTuple.ts +++ b/src/types/unionToTuple.ts @@ -1,32 +1,35 @@ -// Fixed order. - -type UnionToIntersection = (U extends any ? (k: U) => void : never) extends ( - k: infer I, -) => void - ? I +/** + * trick to combine multiple unions of objects into a single object + * only works with objects not primitives + * @param union - Union of objects + * @returns Intersection of objects + */ +type UnionToIntersection = ( + union extends any ? (k: union) => void : never +) extends (k: infer intersection) => void + ? intersection : never; - -type LastOf = - UnionToIntersection T : never> extends () => infer R - ? R +/** + * get last element of union + * @param Union - Union of any types + * @returns Last element of union + */ +type GetUnionLast = + UnionToIntersection< + Union extends any ? () => Union : never + > extends () => infer Last + ? Last : never; - -type Push = [...T, V]; - -export type TuplifyUnionFixedOrder< - T, - L = LastOf, - N = [T] extends [never] ? true : false, -> = true extends N ? [] : Push>, L>; - -// Any order. - -type TuplifyUnionAnyOrderRecurse = { - [S in U]: Exclude extends never - ? [S] - : [...TuplifyUnionAnyOrderRecurse>, S]; -}[U]; - -export type TuplifyUnionAnyOrder = [U] extends [never] - ? [] - : TuplifyUnionAnyOrderRecurse; +/** + * Convert union to tuple + * @param Union - Union of any types, can be union of complex, composed or primitive types + * @returns Tuple of each elements in the union + */ +export type TuplifyUnion = [ + Union, +] extends [never] + ? Tuple + : TuplifyUnion< + Exclude>, + [GetUnionLast, ...Tuple] + >;