Skip to content

Commit

Permalink
Fix types for race()
Browse files Browse the repository at this point in the history
  • Loading branch information
bdougherty committed Jan 10, 2024
1 parent 55efa8c commit 3e1905a
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 15 deletions.
11 changes: 1 addition & 10 deletions lib/all.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Operation, Task } from "./types.ts";
import type { Operation, Task, Yielded } from "./types.ts";
import { spawn } from "./instructions.ts";
import { call } from "./call.ts";

Expand Down Expand Up @@ -52,12 +52,3 @@ export function all<T extends readonly Operation<unknown>[] | []>(
type All<T extends readonly Operation<unknown>[] | []> = {
-readonly [P in keyof T]: Yielded<T[P]>;
};

/**
* Unwrap the type of an `Operation`.
*
* Yielded<Operation<T>> === T
*/
type Yielded<T extends Operation<unknown>> = T extends Operation<infer TYield>
? TYield
: never;
11 changes: 6 additions & 5 deletions lib/race.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Operation } from "./types.ts";
import type { Operation, Yielded } from "./types.ts";
import { action, spawn } from "./instructions.ts";

/**
Expand All @@ -21,16 +21,17 @@ import { action, spawn } from "./instructions.ts";
* });
* ```
*
* @typeParam T the type of the operations that race against each other
* @param operations a list of operations to race against each other
* @returns the value of the fastest operation
*/
export function race<T>(operations: Operation<T>[]): Operation<T> {
return action<T>(function* (resolve, reject) {
export function race<T extends Operation<unknown>>(
operations: readonly T[],
): Operation<Yielded<T>> {
return action<Yielded<T>>(function* (resolve, reject) {
for (let operation of operations) {
yield* spawn(function* () {
try {
resolve(yield* operation);
resolve((yield* operation) as Yielded<T>);
} catch (error) {
reject(error);
}
Expand Down
9 changes: 9 additions & 0 deletions lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -303,3 +303,12 @@ export interface Frame<T = unknown> extends Computation<FrameResult<T>> {
crash(error: Error): Computation<Result<void>>;
destroy(): Computation<Result<void>>;
}

/**
* Unwrap the type of an `Operation`.
*
* Yielded<Operation<T>> === T
*/
export type Yielded<T extends Operation<unknown>> = T extends
Operation<infer TYield> ? TYield
: never;

0 comments on commit 3e1905a

Please sign in to comment.