Description
Suggestion
π Search Terms
Union to Intersection, Generic
https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type
β Viability Checklist
My suggestion meets these guidelines:
- [ x] This wouldn't be a breaking change in existing TypeScript/JavaScript code
- [ x] This wouldn't change the runtime behavior of existing JavaScript code
- [ x] This could be implemented without emitting different JS based on the types of the expressions
- [ x] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- [ x] This feature would agree with the rest of TypeScript's Design Goals.
β Suggestion
A new generic UnionToIntersection<>
which converts from a union to an intersection
π Motivating Example
There are 20k views and 250 upvotes on a Stack Overflow question asking to convert from a union to an intersection.
The top rated answer? Check it out:
type UnionToIntersection<U> =
(U extends any ? (k: U)=>void : never) extends ((k: infer I)=>void) ? I : never
Nobody knows how it works, and it makes debugging a nightmare. But now there is a utility type for it!
(I guess this is how I could announce it on a blog post)
π» Use Cases
In my case, I'm chewing up massive amounts of resources and getting a The inferred type of this node exceeds the maximum length the compiler will serialize. An explicit type annotation is needed.
message because of it.
I don't know what the other ~20k people felt who read that answer. Many were probably curious, but I'm sure many used it for other things.
The most basic example I can imagine is some function that takes an array of objects, then flattens them like so:
function smoosh<T extends object>(objs: Array<T>): UnionToIntersection<T> {
let out = {};
objs.forEach(obj => _.extend(out, obj));
return out;
}
const eg = smoosh([{a: 1}, {b: 2}, {c: 3}]);
eg.a = 1;
eg.b = 2;
eg.c = 3;