typestar

Map over an optional in TypeScript

Applies a function only when the value is not null or undefined.

function maybeMap<T, U>(
  value: T | undefined,
  fn: (value: T) => U,
): U | undefined {
  return value === undefined ? undefined : fn(value);
}

Keywords and builtins used here

The run, in numbers

Lines
6
Characters to type
140
Tokens
43
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 25 seconds.

Type this snippet

Step 11 of 11 in Generic helpers, step 19 of 20 in Generics.

← Previous Next →