I have a method structured as shown below:
class Bar {
public executeInWorker(cb: () => void): void;
public executeInWorker(cb: () => Promise<void>): void | Promise<void>;
public executeInWorker(cb: () => void | Promise<void>): void | Promise<void> {
if (cluster.isPrimary ?? cluster.isMaster) {
return;
}
return cb();
}
}
My goal is to be able to pass in either a synchronous or asynchronous function and have the overloaded method return the correct type (i.e. void
for a sync function and Promise<void>
for an async function).
This implementation works correctly with a sync callback:
// result will be of type void
const result = new Bar().executeInWorker(() => {})
However, it encounters issues when used with an async callback:
// result is expected to be of type Promise<void>, but becomes void
const result = new Bar().executeInWorker(async () => {})
How can I resolve this problem?