UnionToIntersection type
Turns a union into the intersection of its members: A | B gives A & B, to merge the types of a list of mixins or handlers.
ts
import type { UnionToIntersection } from 'utils';Signature
ts
export type UnionToIntersection<U> = (U extends unknown ? (value: U) => void : never) extends (value: infer I) => void
? I
: never;Parameters
| Name | Description |
|---|---|
U | The members to intersect, as a union. |
Example
ts
type All = UnionToIntersection<{ a: 1 } | { b: 2 }>; // { a: 1 } & { b: 2 }Tests
Line coverage: 0 %.
- ✅ intersects the members
Source
src/types/union-to-intersection.ts (on GitHub)
Source code
ts
/**
* Turns a union into the intersection of its members: `A | B` gives `A & B`, to merge the types of a list
* of mixins or handlers.
*
* @template U - The members to intersect, as a union.
* @example
* type All = UnionToIntersection<{ a: 1 } | { b: 2 }>; // { a: 1 } & { b: 2 }
*/
export type UnionToIntersection<U> = (U extends unknown ? (value: U) => void : never) extends (value: infer I) => void
? I
: never;Test file
ts
import type { UnionToIntersection } from './union-to-intersection';
describe('UnionToIntersection', () => {
it('intersects the members', () => {
expectTypeOf<UnionToIntersection<{ a: 1 } | { b: 2 }>>().toEqualTypeOf<{ a: 1 } & { b: 2 }>();
});
});Keywords: union, to, intersection, types, type