From 891d80e7063881e3515863fd816293018956948d Mon Sep 17 00:00:00 2001 From: Retsam Date: Wed, 20 Jun 2018 12:19:31 -0400 Subject: [PATCH] Remove the any from the typings for equalityComparer Replaces the (a: any, b: any) signature for equalityComparer. For observables the signature is `equalityComparer(a: T, b: T)`, but for computeds the more accurate signature is `equalityComparer(a: T | undefined, b: T)`, since the equality comparer is run with the initial computation of a computed, with `undefined` as the first argument. For example: ``` const c = ko.pureComputed(() => 4); c.equalityComparer = (a, b) => { console.log(`Comparing ${a} to ${b}`); return true; }; c(); // Wake up the computed // Prints "Comparing undefined to 4" ``` --- types/knockout/index.d.ts | 6 +++++- types/knockout/test/index.ts | 7 +++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/types/knockout/index.d.ts b/types/knockout/index.d.ts index 5076a05231..1813b29413 100644 --- a/types/knockout/index.d.ts +++ b/types/knockout/index.d.ts @@ -21,7 +21,7 @@ interface KnockoutComputedFunctions extends KnockoutExtensionFunctions { } interface KnockoutObservableFunctions extends KnockoutExtensionFunctions { - equalityComparer(a: any, b: any): boolean; + equalityComparer(a: T, b: T): boolean; } interface KnockoutObservableArrayFunctions extends KnockoutExtensionFunctions { @@ -82,6 +82,10 @@ interface KnockoutComputedStatic { interface KnockoutComputed extends KnockoutObservable, KnockoutComputedFunctions { fn: KnockoutComputedFunctions; + // It's possible for a to be undefined, since the equalityComparer is run on the initial + // computation with undefined as the first argument. This is user-relevant for deferred computeds. + equalityComparer(a: T | undefined, b: T): boolean; + dispose(): void; isActive(): boolean; getDependenciesCount(): number; diff --git a/types/knockout/test/index.ts b/types/knockout/test/index.ts index 38f439efb7..130527818e 100644 --- a/types/knockout/test/index.ts +++ b/types/knockout/test/index.ts @@ -601,6 +601,13 @@ function test_misc() { } } + ko.observable("foo").equalityComparer = (a, b) => { + return a.toLowerCase() === b.toLowerCase(); + }; + ko.computed(() => "foo").equalityComparer = (a, b) => { + return (a !== undefined) && a.toLowerCase() === b.toLowerCase(); + }; + } interface KnockoutBindingHandlers {