Обзор
functionBranching

choose

Branches between two behaviors using a behavior predicate.

Signature

tsSignature
export function choose<I, O1, O2, EP, E1, E2, C extends object>(
predicate: Behavior<I, boolean, EP, C>,
onTrue: Behavior<I, O1, E1, C>,
onFalse: Behavior<I, O2, E2, C>,
): Behavior<I, O1 | O2, EP | E1 | E2, C>;

Imports

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

Type Parameters

I

Shared input type.

O1

True branch output type.

O2

False branch output type.

EP

Predicate domain error type.

E1

True branch domain error type.

E2

False branch domain error type.

C

Custom context type.

Parameters

predicate
Behavior<I, boolean, EP, C>

Behavior that decides which branch to run.

onTrue
Behavior<I, O1, E1, C>

Behavior run when the predicate succeeds with `true`.

onFalse
Behavior<I, O2, E2, C>

Behavior run when the predicate succeeds with `false`.

Returns

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

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

Details

The predicate runs first. If it succeeds with `true`, `onTrue` runs; otherwise `onFalse` runs.

Predicate, true-branch, and false-branch domain errors are preserved in the return type.

Examples

tsExample
const route = choose(isAdmin, loadAdminDashboard, loadUserDashboard);
Behavior

Executable Flow workflow unit.

type

Source

tsflow/choose.ts:26-50
export function choose<I, O1, O2, EP, E1, E2, C extends object>(
predicate: Behavior<I, boolean, EP, C>,
onTrue: Behavior<I, O1, E1, C>,
onFalse: Behavior<I, O2, E2, C>,
): Behavior<I, O1 | O2, EP | E1 | E2, C> {
return async (input: I, context: RuntimeContext<C>) => {
if (context.signal.aborted) {
return resultFromSignal(context.signal);
}
const predicateResult = await runBehavior(predicate, input, context);
if (!predicateResult.ok) {
return predicateResult;
}
if (context.signal.aborted) {
return resultFromSignal(context.signal);
}
const branch = predicateResult.value ? onTrue : onFalse;
return runBehavior(branch as Behavior<I, O1 | O2, E1 | E2, C>, input, context);
};
}