Skip to content

Commit

Permalink
TypeScript - Fix return type when immediate option is set, correctl…
Browse files Browse the repository at this point in the history
…y export interfaces (#8)

Fixes #7
  • Loading branch information
BendingBender authored and sindresorhus committed Apr 21, 2019
1 parent 314c5ef commit 50319f6
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 8 deletions.
19 changes: 16 additions & 3 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
declare namespace debounce {
declare namespace debounceFn {
interface Options {
/**
Time to wait until the `input` function is called.
Expand All @@ -14,6 +14,15 @@ declare namespace debounce {
*/
readonly immediate?: boolean;
}

interface ImmediateOptions extends Options {
readonly immediate: true;
}

interface DebouncedFunction<ArgumentsType extends unknown[], ReturnType> {
(...arguments: ArgumentsType): ReturnType;
cancel(): void;
}
}

/**
Expand All @@ -35,7 +44,11 @@ window.onresize = debounceFn(() => {
*/
declare function debounceFn<ArgumentsType extends unknown[], ReturnType>(
input: (...arguments: ArgumentsType) => ReturnType,
options?: debounce.Options
): ((...arguments: ArgumentsType) => ReturnType | undefined) & {cancel(): void};
options: debounceFn.ImmediateOptions
): debounceFn.DebouncedFunction<ArgumentsType, ReturnType>;
declare function debounceFn<ArgumentsType extends unknown[], ReturnType>(
input: (...arguments: ArgumentsType) => ReturnType,
options?: debounceFn.Options
): debounceFn.DebouncedFunction<ArgumentsType, ReturnType | undefined>;

export = debounceFn;
22 changes: 17 additions & 5 deletions index.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
import {expectType} from 'tsd';
import {expectType, expectError} from 'tsd';
import debounceFn = require('.');

const options: debounceFn.Options = {};
const debounced = debounceFn((string: string) => true);
expectType<((string: string) => boolean | undefined) & {cancel(): void}>(debounced);
expectType<debounceFn.DebouncedFunction<[string], boolean | undefined>>(
debounced
);
expectType<boolean | undefined>(debounced('foo'));
debounced.cancel();

debounceFn((string: string) => true);
debounceFn((string: string) => true, {wait: 100});
debounceFn((string: string) => true, {immediate: true});
const debouncedWithoutOptions = debounceFn((string: string) => true);
expectType<boolean | undefined>(debouncedWithoutOptions('foo'));
expectError<boolean>(debouncedWithoutOptions('foo'));

const debouncedWithWait = debounceFn((string: string) => true, {wait: 100});
expectType<boolean | undefined>(debouncedWithWait('foo'));
expectError<boolean>(debouncedWithWait('foo'));

const debouncedWithImmediate = debounceFn((string: string) => true, {
immediate: true
});
expectType<boolean>(debouncedWithImmediate('foo'));

0 comments on commit 50319f6

Please sign in to comment.