[workerpool] Make WorkerPool.prototype.exec and WorkerPool.prototype.proxy typed. (#41035)

Add Proxy type.
This commit is contained in:
Takashi Tamura
2019-12-16 20:33:06 +09:00
committed by Orta
parent f9ab5155cb
commit f069a444f6
2 changed files with 35 additions and 3 deletions

View File

@@ -3,7 +3,7 @@
// Definitions by: Alorel <https://github.com/Alorel>
// Seulgi Kim <https://github.com/sgkim126>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
// TypeScript Version: 3.1
/// <reference types="node" />
@@ -17,6 +17,10 @@ export interface WorkerPoolStats {
activeTasks: number;
}
export type Proxy<T extends {[k: string]: (...args: any[]) => any}> = {
[M in keyof T]: (...args: Parameters<T[M]>) => Promise<ReturnType<T[M]>>;
};
export interface WorkerPool {
/**
* Execute a function on a worker with given arguments.
@@ -27,14 +31,15 @@ export interface WorkerPool {
* and executed there with the provided parameters. The provided function must be static,
* it must not depend on variables in a surrounding scope.
*/
exec(method: ((...args: any[]) => any) | string, params: any[] | null): Promise<any>;
exec<T extends (...args: any[]) => any>(method: T | string, params: Parameters<T> | null): Promise<ReturnType<T>>;
/**
* Create a proxy for the worker pool.
* The proxy contains a proxy for all methods available on the worker.
* All methods return promises resolving the methods result.
*/
proxy(): Promise<any>;
// tslint:disable-next-line: no-unnecessary-generics
proxy<T extends {[k: string]: (...args: any[]) => any}>(): Promise<Proxy<T>>;
/** Retrieve statistics on workers, and active and pending tasks. */
stats(): WorkerPoolStats;

View File

@@ -37,6 +37,33 @@ pool.exec('foo', null)
.then(() => pool.exec('foo', []))
.then(() => pool.exec(() => {}, null));
function add(a: number, b: number): number {
return a + b;
}
function hello(): string {
return 'hello';
}
pool.exec(add, [1, 2])
.then((c: number) => c);
pool.exec<typeof add>('add', [1, 2])
.then((c: number) => c);
pool.exec(hello, [])
.then((s: string) => s);
const workers = {add, hello};
type IWorkers = typeof workers;
pool.proxy<IWorkers>().then((proxy) => {
proxy.add(1, 2);
proxy.hello();
});
pool.proxy().then((proxy) => {
proxy.add(1, 2);
proxy.hello();
});
new wp.Promise.CancellationError();
new wp.Promise.TimeoutError();