From bc8d8d3c93b6ecb97de2b8fb808e5187f051ae9d Mon Sep 17 00:00:00 2001 From: divdavem Date: Fri, 23 Sep 2022 12:52:23 +0200 Subject: [PATCH] fix: correctly infer the type of the function passed to derived Before this commit, the type of the function passed to derived was not correctly inferred by typescript in the async case. By putting the async case first in the list of overloads of the derived function, it looks like it fixes the issue, and the type is still correctly inferred in the sync case too. --- src/index.spec.ts | 20 ++++++++++++++++++++ src/index.ts | 8 ++++---- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/index.spec.ts b/src/index.spec.ts index de468a6..096785f 100644 --- a/src/index.spec.ts +++ b/src/index.spec.ts @@ -971,6 +971,26 @@ describe('stores', () => { }); }); + it('should infer types automatically in the async case', () => { + const a = writable(1); + const b = writable(2); + const sum = derived( + [a, b], + ([a, b], set) => { + set(a + b); + }, + 0 + ); + expect(get(sum)).toBe(3); + }); + + it('should infer types automatically in the sync case', () => { + const a = writable(1); + const b = writable(2); + const sum = derived([a, b], ([a, b]) => a + b); + expect(get(sum)).toBe(3); + }); + it('should call clean-up function returned in deriveFn with derived', () => { const a = writable(1); const cleanUpFn = jasmine.createSpy('cleanupFn').and.callThrough(); diff --git a/src/index.ts b/src/index.ts index a6a5a7c..bbcd018 100644 --- a/src/index.ts +++ b/src/index.ts @@ -752,13 +752,13 @@ export abstract class DerivedStore< */ export function derived( stores: S, - options: SyncDeriveFn | SyncDeriveOptions, - initialValue?: T + options: AsyncDeriveFn | AsyncDeriveOptions, + initialValue: T ): Readable; export function derived( stores: S, - options: AsyncDeriveFn | AsyncDeriveOptions, - initialValue: T + options: SyncDeriveFn | SyncDeriveOptions, + initialValue?: T ): Readable; export function derived( stores: S,