Skip to content

when() function ​

It returns the original value based on the condition of the first argument or the result of executing the function passed as the second argument.

Signature:

typescript
declare function when<T, S extends T, R>(predicate: (input: T) => input is S, callback: (input: S) => R): (a: T) => R | Exclude<T, S>;

Example ​

typescript
when(
  isNumber,
  () => `This is number`
  100,
); // This is number

with pipe

typescript
pipe(
  100,
  when(
    isNumber,
    () => `This is number`
  )
) // This is number

pipe(
  100,
  when(
    isNumber,
    (value) => value * 2
  )
) // 200

pipe(
  100,
  when(
    isString,
    () => `This is number` // not work
  ),
) // 100

Open Source Code

Released under the Apache-2.0 License.