Skip to content

Commit

Permalink
worker: fix async typing
Browse files Browse the repository at this point in the history
Signed-off-by: Varun Patil <[email protected]>
  • Loading branch information
pulsejet committed Oct 30, 2023
1 parent 8df9c30 commit e1c89f9
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions src/services/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,22 @@ type CommResult = {
reject?: string;
};

/**
* Map of function names to functions.
*/
type FunctionMap = { [name: string]: Function };

/**
* Utility type to convert all methods in an object to async.
*/
type Async<T extends FunctionMap> = {
[K in keyof T]: T[K] extends (...args: infer A) => Promise<infer R>
? (...args: A) => Promise<R>
: T[K] extends (...args: infer A) => infer R
? (...args: A) => Promise<R>
: T[K];
};

/**
* Export methods from a worker to the main thread.
*
Expand All @@ -34,7 +50,7 @@ type CommResult = {
* inline: () => 'bar',
* });
*/
export function exportWorker<T extends { [name: string]: Function }>(handlers: T): T {
export function exportWorker<T extends FunctionMap>(handlers: T): Async<T> {
self.onmessage = async ({ data }: { data: CommRequest }) => {
try {
// Get handler from registrations
Expand All @@ -55,7 +71,7 @@ export function exportWorker<T extends { [name: string]: Function }>(handlers: T
}
};

return null as unknown as T;
return null as unknown as Async<T>;
}

/**
Expand Down

0 comments on commit e1c89f9

Please sign in to comment.