Skip to content

Commit

Permalink
Tighten types for createOptionalCallbackFunction()
Browse files Browse the repository at this point in the history
  • Loading branch information
LoneRifle committed Jul 8, 2023
1 parent 52e4e08 commit 191c6e9
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,25 +210,29 @@ export interface TransformAlgorithm {
* This follows the factory pattern.
* Just call this function, passing the function that you'd like to add a callback version of.
*/
export function createOptionalCallbackFunction<T, A extends any[]>(
export function createOptionalCallbackFunction<T, A extends unknown[]>(
syncVersion: (...args: A) => T
): {
(...args: A): T;
(...args: [...A, ErrorFirstCallback<T>]): void;
} {
return ((...args: any[]): any => {
return ((...args: A | [...A, ErrorFirstCallback<T>]) => {
const lastArg = args[args.length - 1];
if (typeof lastArg === "function") {
const callback = lastArg as ErrorFirstCallback<T>
try {
const result = syncVersion(...(args.slice(0, -1) as A));
(lastArg as (err: null, result: T) => void)(null, result);
callback(null, result);
} catch (err) {
(lastArg as (err: Error) => void)(err instanceof Error ? err : new Error("Unknown error"));
callback(err instanceof Error ? err : new Error("Unknown error"));
}
} else {
return syncVersion(...(args as A));
}
}) as any;
}) as {
(...args: A): T;
(...args: [...A, ErrorFirstCallback<T>]): void;
};
}

declare global {
Expand Down

0 comments on commit 191c6e9

Please sign in to comment.