Skip to content

Commit

Permalink
Improve type inference of the returned function #55
Browse files Browse the repository at this point in the history
  • Loading branch information
chodorowicz committed Nov 13, 2021
1 parent 9490e5d commit 7912b15
Showing 1 changed file with 19 additions and 16 deletions.
35 changes: 19 additions & 16 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,37 @@
/**
* A function that emits a side effect.
*/
export type Procedure = (...args: any[]) => any;

export type Options<TT> = {
export type Options<Result> = {
isImmediate?: boolean;
maxWait?: number;
callback?: (data: TT) => void;
callback?: (data: Result) => void;
};

export interface DebouncedFunction<F extends Procedure> {
(this: ThisParameterType<F>, ...args: Parameters<F>): Promise<ReturnType<F>>;
export interface DebouncedFunction<
Args extends unknown[],
F extends (...args: Args) => any
> {
(this: ThisParameterType<F>, ...args: Args): Promise<ReturnType<F>>;
cancel: (reason?: any) => void;
}

export function debounce<F extends Procedure>(
interface DebouncedPromise<FunctionReturn> {
resolve: (result: FunctionReturn) => void;
reject: (reason?: any) => void;
}

export function debounce<
Args extends unknown[],
F extends (...args: Args) => any
>(
func: F,
waitMilliseconds = 50,
options: Options<ReturnType<F>> = {}
): DebouncedFunction<F> {
): DebouncedFunction<Args, F> {
let timeoutId: ReturnType<typeof setTimeout> | undefined;
const isImmediate = options.isImmediate ?? false;
const callback = options.callback ?? false;
const maxWait = options.maxWait;
let lastInvokeTime = Date.now();

let promises: {
resolve: (x: ReturnType<F>) => void;
reject: (reason?: any) => void;
}[] = [];
let promises: DebouncedPromise<ReturnType<F>>[] = [];

function nextInvokeTimeout() {
if (maxWait !== undefined) {
Expand All @@ -44,7 +47,7 @@ export function debounce<F extends Procedure>(

const debouncedFunction = function (
this: ThisParameterType<F>,
...args: Parameters<F>
...args: Args
) {
const context = this;
return new Promise<ReturnType<F>>((resolve, reject) => {
Expand Down

0 comments on commit 7912b15

Please sign in to comment.