Created
June 17, 2025 23:01
-
-
Save hugoaboud/f852768d169d0a02612ce6bfb4404f69 to your computer and use it in GitHub Desktop.
TypeScript: Union to Intersection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* An efficient TypeScript utility type to transform a union of objects into the intersection of such objects. | |
* | |
* - TypeScript 5.8.2 | |
* - Benchmarked against the similar type declared at [utility-types](https://github.com/piotrwitek/utility-types): | |
* - `utility-types`: ~250ms | |
* - `this`: ~30ms | |
* | |
* - This haven't been deeply tested for correctness yet. | |
*/ | |
type UnionToIntersection<T> = { [K in T as K & string]: K }[any] | |
/** | |
* Benchmark | |
* (Benchmark was performed with a custom tool I haven't published yet, | |
* the used types are described below for reproducing with other tools) | |
*/ | |
type Union = | |
(() => void) | |
| ((a0: string) => void) | |
| ((a0: string, b0: number) => { c0: boolean }) | |
| { b0: number, c0: string } | |
| ({ d0: boolean, e0: Date } & { f0: number }) | |
| { g0: string[] } | |
// | |
// | [1...19] | |
// | |
type utilityTypes_UnionToIntersection<T> = (T extends any | |
? (k: T) => void | |
: never) extends (k: infer I) => void | |
? I | |
: never; | |
// @ts-benchmark(this version) | |
type Intersection = UnionToIntersection<Union> | |
// @ts-benchmark(utility-types version) | |
type utilityTypes_Intersection = utilityTypes_UnionToIntersection<Union> | |
type IsSimilar = | |
(Intersection extends utilityTypes_Intersection ? 'yes' : 'no') | |
| (utilityTypes_Intersection extends Intersection ? 'yes' : 'no') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment