Skip to content

Commit

Permalink
UnionToIntersection: Allow indexing by the resulting type (#682)
Browse files Browse the repository at this point in the history
  • Loading branch information
niieani committed Oct 7, 2023
1 parent 113400b commit 61f2ff9
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
3 changes: 2 additions & 1 deletion source/union-to-intersection.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,5 +56,6 @@ export type UnionToIntersection<Union> = (
// Infer the `Intersection` type since TypeScript represents the positional
// arguments of unions of functions as an intersection of the union.
) extends ((mergedIntersection: infer Intersection) => void)
? Intersection
// The `& Union` is to allow indexing by the resulting type
? Intersection & Union
: never;
7 changes: 6 additions & 1 deletion test-d/union-to-intersection.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {expectAssignable} from 'tsd';
import {expectAssignable, expectType} from 'tsd';
import type {UnionToIntersection} from '../index';

declare const intersection1: UnionToIntersection<{a: string} | {b: number}>;
Expand All @@ -7,3 +7,8 @@ expectAssignable<{a: string; b: number}>(intersection1);
// Creates a union of matching properties.
declare const intersection2: UnionToIntersection<{a: string} | {b: number} | {a: () => void}>;
expectAssignable<{a: string | (() => void); b: number}>(intersection2);

// It's possible to index by the resulting type.
type ObjectsUnion = {a: string; z: string} | {b: string; z: string} | {c: string; z: string};
declare const value: ObjectsUnion[UnionToIntersection<keyof ObjectsUnion>];
expectType<string>(value);

0 comments on commit 61f2ff9

Please sign in to comment.