Skip to content

cases() function

Returns a mapped value based on the first matching predicate. The predicates can return boolean or be type refinements.

If the predicate is a type refinement, the corresponding mapper will receive the narrowed type. Else, the mapper will receive the original type. If there's no match, the input value is returned as is. (if the number of functions is even) Or the default function (the last function without paired predicate) is executed if provided. (if the number of functions is odd)

Signature:

typescript
declare function cases(): (value: unknown) => typeof value;

Returns:

(value: unknown) => typeof value

Example 1

ts
pipe(
  [10, 20, 30],
  map(cases(
    lt(15), (n) => n + 20,
    lt(25), (n) => n + 10,
  )),
  toArray,
) // [30, 30, 30]

Example 2

with type refinement

ts
type A = { a: string; }
type B = A & { b: string; }

pipe(
  [{ a: "A", b: "B" }, { a: "A" }] as A[],
  map(cases(
   (n): n is B => "b" in n, (n) => n.b,
   (n) => n.a,
  )),
 toArray,
) // ["B", "A"]

Open Source Code

Released under the Apache-2.0 License.