Skip to content

Commit

Permalink
Update compare types to work when the input is a generic (#465)
Browse files Browse the repository at this point in the history
  • Loading branch information
dimfeld authored Jun 12, 2022
1 parent b93fcf2 commit fee2bf9
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 6 deletions.
12 changes: 6 additions & 6 deletions packages/collection-compare/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ type Primitive = boolean | string | number | bigint | null | undefined;

declare function compare<T extends Primitive>(value1: T, value2: T): boolean;

declare function compare<T1 extends object, T2 extends T1>(
value1: Exclude<T1, Primitive>,
value2: Exclude<T2, Primitive>
declare function compare<T1 extends object, T2 extends object & T1>(
value1: T1,
value2: T2
): boolean;

declare function compare<T1 extends T2, T2 extends object>(
value1: Exclude<T1, Primitive>,
value2: Exclude<T2, Primitive>
declare function compare<T1 extends object & T2, T2 extends object>(
value1: T1,
value2: T2
): boolean;

export default compare;
5 changes: 5 additions & 0 deletions packages/collection-compare/index.tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ compare(obj1, { b: 3, a: 2 });
compare([1, [2, { a: 4 }], 4], [1, [2, { a: 4 }]]);
compare([1, [2, { a: 4 }], 4], [1, [2, { a: 4 }], 4]);
compare(NaN, NaN);
const compareIt = <T extends object>(a: T, b: T) => compare(a, b);

// Not okay
// @ts-expect-error
Expand All @@ -60,6 +61,10 @@ compare(obj2, obj1);
// @ts-expect-error
compare(obj1, obj2);
// @ts-expect-error
compare(obj1, num1);
// @ts-expect-error
compare(num1, obj1);
// @ts-expect-error
compare(NaN, "abc");
// @ts-expect-error
compare(funcA, funcB);
Expand Down
1 change: 1 addition & 0 deletions packages/collection-compare/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"module": "index.mjs",
"exports": {
".": {
"types": "./index.d.ts",
"require": "./index.js",
"default": "./index.mjs"
}
Expand Down

0 comments on commit fee2bf9

Please sign in to comment.