Skip to content

Commit

Permalink
fix: correctly infer the type of the function passed to derived
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
divdavem committed Sep 23, 2022
1 parent 8bdf3f2 commit bc8d8d3
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
20 changes: 20 additions & 0 deletions src/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
8 changes: 4 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -752,13 +752,13 @@ export abstract class DerivedStore<
*/
export function derived<T, S extends SubscribableStores>(
stores: S,
options: SyncDeriveFn<T, S> | SyncDeriveOptions<T, S>,
initialValue?: T
options: AsyncDeriveFn<T, S> | AsyncDeriveOptions<T, S>,
initialValue: T
): Readable<T>;
export function derived<T, S extends SubscribableStores>(
stores: S,
options: AsyncDeriveFn<T, S> | AsyncDeriveOptions<T, S>,
initialValue: T
options: SyncDeriveFn<T, S> | SyncDeriveOptions<T, S>,
initialValue?: T
): Readable<T>;
export function derived<T, S extends SubscribableStores>(
stores: S,
Expand Down

0 comments on commit bc8d8d3

Please sign in to comment.