From 809697d009059bf177c0d556009eaee121dc2ef6 Mon Sep 17 00:00:00 2001 From: Federico Brigante Date: Fri, 29 Nov 2019 17:56:52 +0700 Subject: [PATCH] Support overloaded functions (TypeScript types) (#48) --- index.d.ts | 7 ++++--- index.test-d.ts | 20 +++++++++++++++----- package.json | 2 +- 3 files changed, 20 insertions(+), 9 deletions(-) diff --git a/index.d.ts b/index.d.ts index 8dfd03c..b958f14 100644 --- a/index.d.ts +++ b/index.d.ts @@ -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 - ): (...arguments: ArgumentsType) => ReturnType; + ): FunctionToMemoize; /** Clear all cached data of a memoized function. diff --git a/index.test-d.ts b/index.test-d.ts index acb5ca8..4082943 100644 --- a/index.test-d.ts +++ b/index.test-d.ts @@ -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(mem(fn)); +expectType(mem(fn, {maxAge: 1})); +expectType(mem(fn, {cacheKey: (...arguments_) => arguments_})); +expectType( mem( fn, {cacheKey: (arguments_) => arguments_, cache: new Map<[string], {data: boolean; maxAge: number}>()}) ); -expectType<(string: string) => boolean>( +expectType( 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(mem(overloadedFn)); +expectType(mem(overloadedFn)(true)); +expectType(mem(overloadedFn)(false)); + mem.clear(fn); diff --git a/package.json b/package.json index a4ddd18..1ab3b64 100644 --- a/package.json +++ b/package.json @@ -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" } }