Skip to main content

Unwrapping

Prefer safe extractors

MethodWhen emptyWhen present
getOrElse(() => x)returns x from thunkreturns value
getOrReturn(x)returns xreturns value
getOrUndefined()undefinedvalue
get()throwsvalue

Use lazy getOrElse when the default is expensive:

opt.getOrElse(() => computeDefault());

Use getOrReturn for constants:

opt.getOrReturn(-1);

get() — use sparingly

Some('ok').get(); // 'ok'
None.get(); // throws Error: No such element

Only call get() when you have already checked isDefined, or immediately after a branch that narrows the type in your own code.

Interop patterns

With async-data:

import { Option } from '@ekz/option';
import type { AsyncData } from '@ekz/async-data';

function toUser(data: AsyncData<User>): Option<User> {
return data.toOption();
}

With nullable APIs:

const name = Option.of(apiResponse?.name).getOrReturn('Anonymous');

With arrays:

const first = Option.of(items[0]);

Anti-patterns

  • Using get() instead of getOrElse / getOrUndefined
  • Converting to undefined and back repeatedly — stay in Option through the pipeline
  • Using Option.of when you mean Some and the value must not be coerced from null