Skip to content

Native Generic for converting from Union to Intersection #45132

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
SephReed opened this issue Jul 21, 2021 · 2 comments
Closed

Native Generic for converting from Union to Intersection #45132

SephReed opened this issue Jul 21, 2021 · 2 comments

Comments

@SephReed
Copy link

SephReed commented Jul 21, 2021

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;
@MartinJohns
Copy link
Contributor

Duplicate of #29594. Used search terms: union intersection type in:title.

@SephReed
Copy link
Author

@MartinJohns thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants