Skip to content

Commit

Permalink
Support overloaded functions (TypeScript types) (#48)
Browse files Browse the repository at this point in the history
  • Loading branch information
fregante authored Nov 29, 2019
1 parent b154f53 commit 809697d
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 9 deletions.
7 changes: 4 additions & 3 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,12 @@ declare const mem: {
<
ArgumentsType extends unknown[],
ReturnType,
CacheKeyType
CacheKeyType,
FunctionToMemoize = (...arguments: ArgumentsType) => ReturnType
>(
fn: (...arguments: ArgumentsType) => ReturnType,
fn: FunctionToMemoize,
options?: mem.Options<ArgumentsType, CacheKeyType, ReturnType>
): (...arguments: ArgumentsType) => ReturnType;
): FunctionToMemoize;

/**
Clear all cached data of a memoized function.
Expand Down
20 changes: 15 additions & 5 deletions index.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,27 @@ import mem = require('.');

const fn = (string: string) => true;

expectType<(string: string) => boolean>(mem(fn));
expectType<(string: string) => boolean>(mem(fn, {maxAge: 1}));
expectType<(string: string) => boolean>(mem(fn, {cacheKey: (...arguments_) => arguments_}));
expectType<(string: string) => boolean>(
expectType<typeof fn>(mem(fn));
expectType<typeof fn>(mem(fn, {maxAge: 1}));
expectType<typeof fn>(mem(fn, {cacheKey: (...arguments_) => arguments_}));
expectType<typeof fn>(
mem(
fn,
{cacheKey: (arguments_) => arguments_,
cache: new Map<[string], {data: boolean; maxAge: number}>()})
);
expectType<(string: string) => boolean>(
expectType<typeof fn>(
mem(fn, {cache: new Map<[string], {data: boolean; maxAge: number}>()})
);

/* Overloaded function tests */
function overloadedFn(parameter: false): false;
function overloadedFn(parameter: true): true;
function overloadedFn(parameter: boolean): boolean {
return parameter;
}
expectType<typeof overloadedFn>(mem(overloadedFn));
expectType<true>(mem(overloadedFn)(true));
expectType<false>(mem(overloadedFn)(false));

mem.clear(fn);
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
"ava": "^2.4.0",
"delay": "^4.1.0",
"serialize-javascript": "^2.1.0",
"tsd": "^0.10.0",
"tsd": "^0.11.0",
"xo": "^0.25.3"
}
}

0 comments on commit 809697d

Please sign in to comment.