josdejong/workerpool

`exec` generic type def doubly wrapped `Promise`?

Open

#485 opened on Jan 29, 2025

View on GitHub
 (4 comments) (0 reactions) (0 assignees)JavaScript (164 forks)github user discovery
enhancementhelp wanted

Repository metrics

Stars
 (2,297 stars)
PR merge metrics
 (PR metrics pending)

Description

Currently the type definition for exec looks like this:

exec<T extends (...args: any[]) => any>(method: string | T, params?: Parameters<T> | null | undefined, options?: import("./types.js").ExecOptions | undefined): Promise<ReturnType<T>>;

Note the Promise<ReturnType<T>>. I think this unnecessarily wraps the ReturnType in a Promise when the return type already is a promise. I think it should be something like Promisify<ReturnType<T>> and type Promisify<T> = T extends Promise<any> ? T : Promise<T>; (wraps type in promise, but only if not already a promise).

I pretty sure it should be like this, because just testing out...

// worker

export const encode = async (blah: any) => {
  const encoder = await createEncoder();
  // ...
  return new Blob();
};

export type Encode = typeof encode;

workerpool.worker({ encode });

// consumer

import EncodeWorker from "./encode.worker?worker&url";
import { Encode } from "./encode.worker.ts";

const encoderPool = workerpool.pool(EncodeWorker);
const getBlob = (blah: any) =>
  encoderPool.exec<Encode>("encode", [blah]);

// test

getBlob(blah).then((result) => console.log(result));

Typescript says result is type Promise<Blob>, but console log shows just Blob. I didn't look at the exec implementation, but the result is definitely just a blob, so the typing must be wrong.

Contributor guide