Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions source/merge.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import type {OmitIndexSignature} from './omit-index-signature.d.ts';
import type {PickIndexSignature} from './pick-index-signature.d.ts';
import type {Simplify} from './simplify.d.ts';
import type {If} from './if.d.ts';
import type {IsEqual} from './is-equal.d.ts';

// Merges two objects without worrying about index signatures.
type SimpleMerge<Destination, Source> = Simplify<{
Expand Down Expand Up @@ -47,11 +49,14 @@ Note: If you want a merge type that more accurately reflects the runtime behavio
export type Merge<Destination, Source> =
Destination extends unknown // For distributing `Destination`
? Source extends unknown // For distributing `Source`
? Simplify<
SimpleMerge<PickIndexSignature<Destination>, PickIndexSignature<Source>>
& SimpleMerge<OmitIndexSignature<Destination>, OmitIndexSignature<Source>>
>
? If<IsEqual<Destination, Source>, Destination, _Merge<Destination, Source>>
: never // Should never happen
: never; // Should never happen

export type _Merge<Destination, Source> =
Simplify<
SimpleMerge<PickIndexSignature<Destination>, PickIndexSignature<Source>>
& SimpleMerge<OmitIndexSignature<Destination>, OmitIndexSignature<Source>>
>;

export {};
10 changes: 10 additions & 0 deletions test-d/merge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,3 +187,13 @@ expectType<
{[x: number]: number; foo: number} | {bar: boolean; baz: boolean}
>,
);

// Idempotency
type TestIntersectionObject = {a: string} & {b: string};
// Note: If `Merge` simplified `TestIntersectionObject` to `{a: string; b: string}` then the following test would fail,
// because `expectType` doesn't consider `{a: string; b: string}` equal to `{a: string} & {b: string}`.
expectType<TestIntersectionObject>({} as Merge<TestIntersectionObject, TestIntersectionObject>);

// Idempotency: Unions
expectType<TestIntersectionObject | {a: string; b: string; c: string}>({} as Merge<TestIntersectionObject | {c: string}, TestIntersectionObject>);
expectType<TestIntersectionObject | {a: string; b: string; c: string}>({} as Merge<TestIntersectionObject, TestIntersectionObject | {c: string}>);