Обзор
functionBranching

when

Branches between two behaviors using a predicate function.

Signature

tsSignature
export function when<I, O1, O2, E1, E2, C extends object>(
predicate: (input: I, context: RuntimeContext<C>) => Awaitable<boolean>,
branches: {
yes: Behavior<I, O1, E1, C>;
no: Behavior<I, O2, E2, C>;
},
): Behavior<I, O1 | O2, E1 | E2, C>;

Imports

tsImport
import { when } from "@/lib/flow/when";
import { when } from "@/lib/flow";

Type Parameters

I

Shared input type.

O1

Yes branch output type.

O2

No branch output type.

E1

Yes branch domain error type.

E2

No branch domain error type.

C

Custom context type.

Parameters

predicate
(input: I, context: RuntimeContext<C>) => Awaitable<boolean>

Function that chooses the branch.

branches
{ yes: Behavior<I, O1, E1, C>; no: Behavior<I, O2, E2, C>; }

`yes` and `no` behaviors.

Returns

A behavior producing either branch output and either branch domain error.

Return type
Behavior<I, O1 | O2, E1 | E2, C>

Details

`when` is a convenience wrapper around `choose` for predicates that can be expressed as ordinary

synchronous or asynchronous functions.

Examples

tsExample
const route = when((user) => user.role === "admin", {
yes: loadAdminDashboard,
no: loadUserDashboard,
});
Awaitable

Represents a value that may be returned directly or through a Promise.

type
Behavior

Executable Flow workflow unit.

type
choose

Branches between two behaviors using a behavior predicate.

function
input

Creates an identity behavior for starting typed pipelines.

function

Source

tsflow/when.ts:30-42
export function when<I, O1, O2, E1, E2, C extends object>(
predicate: (input: I, context: RuntimeContext<C>) => Awaitable<boolean>,
branches: {
yes: Behavior<I, O1, E1, C>;
no: Behavior<I, O2, E2, C>;
},
): Behavior<I, O1 | O2, E1 | E2, C> {
const predicateTask = task<I, boolean, never, C>(async (input, context) =>
context.ok(await predicate(input, context)),
);
return choose(predicateTask, branches.yes, branches.no);
}