Class Opt<T>Abstract

Generic container class. It either holds exactly one value - Some, or no value - None (empty).

It simplifies working with possibly empty values and provides many methods/functions which allow creation of processing pipelines (commonly known as "fluent API" in OOP or chain of reverse applications in FP).

Typeparam

T Wrapped value type.

Type Parameters

  • T

Hierarchy

Properties

fromObject: FromObjectFn = ...

Converts an object to Opt.

Example

Opt.fromObject({value: 4}) // Some(4)
Opt.fromObject({id: 4, something: '?'}, 'id') // Some(4)
Opt.fromObject({value: null}) // None

Param

Param

toObject: ToObjectFn<T> = ...

Converts Opt to an object.

Example

opt(1).toObject() // {value: 1}
opt(undefined).toObject() // {value: null}
opt(undefined).toObject('id') // {id: null}

Param

mapFlow: MapFlowInClassFn<T> = ...

Similar to Opt.map, but supports more functions which are called in succession, each on a result of a previous one.

Example

const sq = (x: number) => x * x;
const dec = (x: number) => x - 1;
opt(4).mapFlow(sq, dec) // Some(15)
opt(null).mapFlow(sq, dec) // None

See

mapFlow

Param

act: ActInClassFn<T> = ...

Similar to Opt.chain (in other languages called bind or >>=), but supports more functions passed at once (resembles do notation in Haskell). It is used to model a sequence of operations where each operation can fail (can return None).

// does addition when first argument is number
const f1 =
(x: string | number) => (y: number) => opt(x).narrow(isNumber).map(z => z + y);
// passes only even numbers
const f2 = (x: number): Opt<number> => x % 2 === 0 ? opt(x) : none;

opt(0).act( // Some(0)
f1(-2), // Some(-2)
f2, // Some(-2)
optNegative, // None
); // None

opt(0).act( // Some(0)
f1(1), // Some(1)
f2, // None
optNegative, // won't get called, still None
); // None

opt(3).act( // Some(3)
f1(1), // Some(4)
f2, // Some(4)
optNegative, // Some(4)
); // Some(4)

See

act

Param

chainFlow: ActInClassFn<T> = ...

Alias

Opt.act

See

chainFlow

Param

actToOpt: ActToOptInClassFn<T> = ...

Similar to act, but functions return empty values instead of Opt. It is useful for typical JavaScript functions (e.g. lodash), properly handles undefined/null/NaN at any point of the chain.

Example

import {find} from 'lodash/fp';

const data = [{}, {f: true, a: [{b: 7, c: 1}]}, {a: [{}]}];
opt(data).actToOpt(
find(x => Boolean(x?.f)), // {f: true, a: [{b: 7, c: 1}]}
x => x?.a, // [{b: 7, c: 1}]
find(x => x.b === 8) // undefined
); // None

See

actToOpt

Param

chainToOptFlow: ActToOptInClassFn<T> = ...
pipe: PipeInClassFn<T> = ...

Applies passed function to this instance and returns function result. Also known as a reverse function application, |> (Reason/ReScript, F#, OCaml), & (Haskell), # (PureScript) or a pipe operator.

Example

some(1).pipe(x => x.isEmpty) // false
none.pipe(x => x.isEmpty) // true

Supports multiple functions.

Example

opt(1).pipe( // Some(1)
x => x.isEmpty, // false
x => !x, // true
) // true

See

pipe

Param

Functions in call chain

const: ConstInClassFn<T> = ...

Constructs a function which returns a value for Some or an empty value for None (default is null). Optionally takes an empty value as a parameter.

Example

opt(1).const()() // 1
opt(undefined).const()() // null

// custom empty value
opt(NaN).const(undefined)() // undefined

Accessors

  • get length(): 0 | 1
  • 1 for Some, 0 for None.

    Important: This is not the wrapped value's length. E.g., opt([1,2,3]).length === 1. Use Opt.lengthIn for array/string length of the wrapped value.

    Returns 0 | 1

  • get end(): void
  • No-op terminator used to end imperative chains.

    Returns void

    Imperative

    Example

    const f = (x: unknown): void => opt(x).onBoth(noop, noop).end;
    // same as
    const g = (x: unknown): void => { opt(x).onBoth(noop, noop); };

Methods

  • Returns the length of a string or array wrapped in an Opt.

    Type Parameters

    • R extends Opt<number>

    Parameters

    • this: Opt<string | readonly unknown[]>

    Returns R

    Example

    opt('hello').lengthIn() // Some(5)
    opt([1, 2, 3]).lengthIn() // Some(3)
    opt('').lengthIn() // Some(0)
    opt([]).lengthIn() // Some(0)
    none.lengthIn() // None
  • Create Opt instance from an array of one or zero items.

    Opt.fromArray([]) // None
    Opt.fromArray([1]) // Some(1)

    Type Parameters

    • T

    Parameters

    • x: readonly [] | readonly [T]

    Returns Opt<T>

  • Converts Opt to an array.

    Returns [] | [T]

    Example

    some(1).toArray() // [1]
    none.toArray() // []

    See

    toArray

  • Applies function to the wrapped value and returns a new instance of Some.

    some(1).map(x => x + 1) // Some(2)
    none.map(x => x + 1) // None

    Type Parameters

    • U

    Parameters

    • f: ((_) => U)
        • (_): U
        • Parameters

          • _: T

          Returns U

    Returns Opt<U>

    See

    • onSome for imperative variant (for use with callback)
    • map
  • Applies a map function to an array inside.

    Type Parameters

    • U

    • R

    Parameters

    • this: Opt<U[]>
    • f: ((x) => R)
        • (x): R
        • Parameters

          • x: U

          Returns R

    Returns Opt<R[]>

    Example

    opt([1, 2, 3]).mapIn(x => x + 1) // Some([2, 3, 4])
    
  • Maps over an array inside the Opt with index.

    Type Parameters

    • U

    • R

    Parameters

    • this: Opt<readonly U[]>
    • f: ((x, i) => R)
        • (x, i): R
        • Parameters

          • x: U
          • i: number

          Returns R

    Returns Opt<readonly R[]>

    Example

    opt(['a', 'b']).mapWithIndexIn((x, i) => x + i) // Some(['a0', 'b1'])
    none.mapWithIndexIn((x, i) => x + i) // None
  • Maps over a property of objects in an array inside the Opt, discarding nulls and undefined values.

    Type Parameters

    • K extends string

    • V

    Parameters

    • this: Opt<(undefined | null | {
          [key in string]?: V
      })[]>
    • key: K

    Returns Opt<V[]>

    Example

    opt([{data: 1}, {}, {data: 2}, null]).mapPropNakedIn('data') // Some([1, 2])
    
  • Maps over characters in a string wrapped in an Opt.

    Parameters

    • this: Opt<string>
    • f: ((c) => string)
        • (c): string
        • Parameters

          • c: string

          Returns string

    Returns Opt<string>

    Example

    opt('hello').mapStr(c => c.toUpperCase()) // Some('HELLO')
    opt('').mapStr(c => c.toUpperCase()) // Some('')
    none.mapStr(c => c.toUpperCase()) // None

    See

    mapStr

  • Similar to Opt.map, but function is expected to return Opt which will be returned. Useful for including steps which may fail or return no value.

    some(1).flatMap(x => x === 1 ? none : some(x + 1)) // None
    none.flatMap(x => some(1)) // None

    Type Parameters

    • U

    Parameters

    • f: ((_) => Opt<U>)
        • (_): Opt<U>
        • Parameters

          • _: T

          Returns Opt<U>

    Returns Opt<U>

  • Applies a flatMap function to an array inside.

    Type Parameters

    • U

    • R

    Parameters

    • this: Opt<U[]>
    • f: ((x) => R[])
        • (x): R[]
        • Parameters

          • x: U

          Returns R[]

    Returns Opt<R[]>

    Example

    opt([1, 2]).flatMapIn(x => [x, x * 2]) // Some([1, 2, 2, 4])
    
  • Type Parameters

    • U

    • R

    Parameters

    • this: Opt<U[]>
    • f: ((x) => R[])
        • (x): R[]
        • Parameters

          • x: U

          Returns R[]

    Returns Opt<R[]>

  • Combination of Opt.flatMap and opt functions.

    Type Parameters

    • U

    Parameters

    • f: ((_) => undefined | null | U)
        • (_): undefined | null | U
        • Parameters

          • _: T

          Returns undefined | null | U

    Returns OptSafe<U>

    Example

    some(1).chainToOpt(x => x === 1 ? null : x + 1) // None
    some(2).chainToOpt(x => x === 1 ? null : x + 1) // Some(3)

    See

    chainToOpt

  • Joins (flattens) nested Opt instance, turning an Opt<Opt<T>> into an Opt<T>. This is equivalent to calling flatMap with the identity function: .join() ~ .flatMap(id).

    Type Parameters

    • U

    Parameters

    Returns Opt<U>

    Example

    const nestedOpt: Opt<Opt<number>> = opt(opt(42)); // Some(Some(42))
    const flattenedOpt: Opt<number> = nestedOpt.join(); // Some(42)
  • Returns value when Some, throws error otherwise.

    Parameters

    • message: string

      Error message.

    Returns T

    Example

    opt(null).orCrash('unexpected empty value') // crashes with Error('unexpected empty value')
    opt(1).orCrash('unexpected empty value') // 1
    opt(null).orCrash(() => new CustomException()) // crashes with CustomException

    See

    orCrash

  • Parameters

    • errorFactory: (() => unknown)
        • (): unknown
        • Returns unknown

    Returns T

  • Crash when called on None, pass Opt instance on Some.

    Parameters

    • errorFactory: (() => unknown)
        • (): unknown
        • Returns unknown

    Returns Some<T>

    Example

    some(1).someOrCrash('fail') // Some(1)
    none.someOrCrash('fail') // throws
    none.someOrCrash(() => new Error('fail')) // throws Error('fail')

    See

    someOrCrash

  • Parameters

    • msg: string

    Returns Some<T>

  • Returns value for Some or undefined for None.

    Returns undefined | T

    Example

    some(1).orUndef() // 1
    none.orUndef() // undefined

    See

    orUndef

  • Returns value for Some or null for None.

    Returns null | T

    Example

    some(1).orNull() // 1
    none.orNull() // null

    See

    orNull

  • Returns inner value for Some, false for None.

    Returns false | T

    Example

    some(1).orFalse() // 1
    none.orFalse() // false

    See

  • Returns inner value for Some, true for None.

    Returns true | T

    Example

    some(1).orTrue() // 1
    none.orTrue() // true

    See

  • Returns inner value for Some, NaN for None.

    Returns number | T

    Example

    some(1).orNaN() // 1
    none.orNaN() // NaN

    See

    orNaN

  • Applies appropriate function and returns result from the function.

    Type Parameters

    • R

    Parameters

    • someCase: ((x) => R)

      Processing function for Some.

        • (x): R
        • Parameters

          • x: T

          Returns R

    • noneCase: (() => R)

      Processing function for None.

        • (): R
        • Returns R

    Returns R

    Example

    some(1).caseOf(x => x + 1, () => 0) // 2
    none.caseOf(x => x + 1, () => 0) // 0

    See

  • Reduces the Opt instance to a single value by applying a function to the value inside Some or returning a default value for None.

    Type Parameters

    • R

    Parameters

    • someCase: ((x) => R)

      Function to apply to the value inside Some.

        • (x): R
        • Parameters

          • x: T

          Returns R

    • noneCase: R

      Default value to return for None.

    Returns R

    Example

    opt(1).fold(x => x + 1, 0) // 2
    none.fold(x => x + 1, 0) // 0
  • Applies a reducer function to an array within an Opt instance, combining its elements into a single value using the array's reduce method.

    Type Parameters

    • U

    • R

    Parameters

    • this: Opt<U[]>
    • f: ((acc, x) => R)
        • (acc, x): R
        • Parameters

          • acc: R
          • x: U

          Returns R

    • initial: R

    Returns Opt<R>

    Example

    opt([1, 2, 3]).foldIn((acc, x) => acc + x, 0) // Some(6)
    none.foldIn((acc, x) => acc + x, 0) // None
  • Calls appropriate callback and returns without change current instance of Opt.

    Parameters

    • onSome: ((x) => void)
        • (x): void
        • Parameters

          • x: T

          Returns void

    • onNone: (() => void)
        • (): void
        • Returns void

    Returns Opt<T>

    Example

    // prints 1, returns some(1)
    some(1).onBoth(x => console.log(x), () => console.log('none'))

    // prints "none", returns none
    none.onBoth(x => console.log(x), () => console.log('none'))

    See

    Imperative

  • Calls f on Some with its value, does nothing for None.

    Parameters

    • f: ((x) => void)
        • (x): void
        • Parameters

          • x: T

          Returns void

    Returns Opt<T>

    Imperative

  • Calls f on None, does nothing for Some.

    Parameters

    • f: (() => void)
        • (): void
        • Returns void

    Returns Opt<T>

    Imperative

  • Compares inner value with given value using ===. Always false for None.

    some(1).contains(1) // true
    some(0).contains(1) // false
    none.contains(undefined) // false

    Similar to JavaScript Array#includes method.

    Parameters

    • x: T

    Returns boolean

  • Checks if an array inside the Opt contains the given element.

    Type Parameters

    • U

    Parameters

    • this: Opt<readonly U[]>
    • x: U

      Element to search for.

    Returns boolean

    Example

    opt([1, 2, 3]).hasIn(2) // true
    opt([1, 2, 3]).hasIn(4) // false
    none.hasIn(1) // false

    See

    has

  • Type Parameters

    • U

    Parameters

    • this: Opt<readonly U[]>
    • x: U

    Returns boolean

    Alias

    Opt.hasIn

  • Checks if the value inside the Opt is an element of the given array. Flipped version of Opt.hasIn.

    Parameters

    • haystack: readonly T[]

      The array to check against

    Returns boolean

    true if the value is in the array, false otherwise

    Example

    opt(1).elemOfIn([1, 2, 3]) // true
    opt(4).elemOfIn([1, 2, 3]) // false
    none.elemOfIn([1, 2, 3]) // false
    opt('cow').elemOfIn(['dog', 'cow', 'pig']) // true
    opt('cat').elemOfIn(['dog', 'cow', 'pig']) // false
    none.elemOfIn(['dog', 'cow', 'pig']) // false

    See

    elemOf

  • Checks if the string value inside this Opt is a substring of the given string.

    Parameters

    • this: Opt<string>
    • haystack: string

      The string to search in

    Returns boolean

    true if the value is a substring of the haystack, false otherwise

    Example

    opt('ab').elemOfStrIn('abc') // true
    opt('a').elemOfStrIn('def') // false
    none.elemOfStrIn('abc') // false

    See

  • Checks if the array inside the Opt is empty or if the instance is None.

    Parameters

    • this: Opt<readonly unknown[]>

    Returns boolean

    Example

    opt([1, 2, 3]).isEmptyIn() // false
    opt([]).isEmptyIn() // true
    none.isEmptyIn() // true
  • Applies p to inner value and passes result. Always false for None.

    some(0).exists(x => x > 0) // false
    some(1).exists(x => x > 0) // true
    none.exists(x => x > 0) // false

    Parameters

    • p: ((x) => boolean)

      Predicate.

        • (x): boolean
        • Parameters

          • x: T

          Returns boolean

    Returns boolean

    See

    exists

  • Checks if any element in the array inside the Opt satisfies the predicate. Similar to Array.some from JavaScript.

    Type Parameters

    • U

    Parameters

    • this: Opt<U[]>
    • p: ((x) => boolean)
        • (x): boolean
        • Parameters

          • x: U

          Returns boolean

    Returns Opt<boolean>

    Example

    opt([1]).existsIn(x => x > 0) // Some(true)
    opt([-1]).existsIn(x => x > 0) // Some(false)
    opt([]).existsIn(x => x > 0) // Some(false)
    none.existsIn(x => x > 0) // None
  • Applies p to inner value and passes result. Always true for None.

    Parameters

    • p: ((x) => boolean)

      Predicate.

        • (x): boolean
        • Parameters

          • x: T

          Returns boolean

    Returns boolean

    Example

    some(0).forAll(x => x > 0) // false
    some(1).forAll(x => x > 0) // true
    none.forAll(x => x > 0) // true

    See

    forAll

  • Checks if all elements in the array inside the Opt satisfy the predicate. Similar to Array.every from JavaScript.

    Type Parameters

    • U

    Parameters

    • this: Opt<U[]>
    • p: ((x) => boolean)
        • (x): boolean
        • Parameters

          • x: U

          Returns boolean

    Returns Opt<boolean>

    Example

    opt([1]).forAllIn(x => x > 0) // Some(true)
    opt([-1]).forAllIn(x => x > 0) // Some(false)
    opt([]).forAllIn(x => x > 0) // Some(true)
    none.forAllIn(x => x > 0) // None
  • Get inner value of Some, or use passed def value for None.

    Parameters

    • def: T

      Default value.

    Returns T

    Example

    some(1).orElse(2) // 1
    none.orElse(2) // 2

    See

    orElse

  • Get inner value of Some, or lazily use passed def value for None.

    If a computation of a default value is not expensive (or has been already computed), use orElse instead.

    Parameters

    • def: (() => T)
        • (): T
        • Returns T

    Returns T

    Example

    some(1).orElseLazy(() => 2) // 1
    none.orElseLazy(() => 2) // 2

    See

    orElseLazy

  • Less strict version of orElse.

    Type Parameters

    • U

    Parameters

    • def: U

    Returns T | U

    Example

    opt(1).orElse(true); // TS2345: Argument of type 'boolean' is not assignable to parameter of type 'number'.
    opt(1).orElseAny(true) // 1 :: number | boolean
  • Return this for Some, def for None. It represents an alternative on Opts.

    Parameters

    Returns Opt<T>

    Example

    none.alt(some(0)) // Some(0)
    opt(1).alt(some(0)) // Some(1)
    none.alt(none) // None
    some(1).alt(none) // Some(1)

    Example

    It can be used to pick first from given possibly missing alternatives.

    type Handler = (_: number) => void;
    const userHandler: Opt<Handler> = opt(a => console.log('user handling', a));
    const systemHandler: Opt<Handler> = opt(a => console.log('system handling', a));
    const backupHandler: Opt<Handler> = opt(a => console.log('backup handling', a));
    const panicHandler: Handler = a => console.log('PANIC handling', a);
    const handler =
    userHandler
    .alt(systemHandler)
    .alt(backupHandler)
    .orElse(panicHandler);
    handler(250 + 64); // prints "user handling 314"
  • Return this for Some, def wrapped in opt for None.

    Parameters

    Returns OptSafe<T>

    Example

    const inputNull: number | null = null as number | null;
    opt(inputNull).altOpt(null) // None
    opt(inputNull).altOpt(1) // Some(1)
    opt(2).altOpt(1) // Some(2)

    Example

    type Handler = (_: number) => void;
    const userHandler: Handler | null = a => console.log('user handling', a);
    const systemHandler: Handler | null = a => console.log('system handling', a);
    const backupHandler: Handler | null = a => console.log('backup handling', a);
    const panicHandler: Handler = a => console.log('PANIC handling', a);
    const handler =
    opt(userHandler)
    .altOpt(systemHandler)
    .altOpt(backupHandler)
    .orElse(panicHandler);
    handler(250 + 64); // prints "user handling 314"
  • Similar to caseOf but doesn't unwrap value.

    Type Parameters

    • U

    Parameters

    • someF: ((_) => U)
        • (_): U
        • Parameters

          • _: T

          Returns U

    • noneF: (() => U)
        • (): U
        • Returns U

    Returns Opt<U>

    Example

    some(1).bimap(x => x + 1, () => 0) // Some(2)
    none.bimap(x => x + 1, () => 0) // Some(0)

    See

    bimap

  • Similar to Opt.bimap, but accepts functions returning Opt.

    Type Parameters

    • U

    Parameters

    • someF: ((_) => Opt<U>)
        • (_): Opt<U>
        • Parameters

          • _: T

          Returns Opt<U>

    • noneF: (() => Opt<U>)

    Returns Opt<U>

    Example

    some(1).flatBimap(x => some(x+1), () => some(0)) // Some(2)
    none.flatBimap(x => some(x+1), () => some(0)) // Some(0)
    some(5).flatBimap(x => none, () => some(0)) // None

    See

    flatBimap

  • Formats Opt to string. In case of Some inner value is converted using JSON.stringify.

    Returns string

    Example

    some(1).toString() // 'Some(1)'
    none.toString() // 'None'

    See

    toString

  • Joins two optional values to a pair. If either of them is None then the result is None.

    Type Parameters

    • U

    Parameters

    Returns Opt<[T, U]>

    Example

    some(1).zip(some(true)) // Some([1, true])
    some(1).zip(none) // None
    none.zip(some(1)) // None
    none.zip(none) // None

    Example

    const formatAddress =
    (streetName?: string, streetNumber?: number): string =>
    opt(streetName).zip(opt(streetNumber)).map(join(' ')).orElse('');
    formatAddress('Strawberry', '12') // 'Strawberry 12'
    formatAddress('Strawberry', undefined) // ''
    formatAddress(undefined, '12') // ''
    formatAddress(undefined, undefined) // ''

    See

    zip

  • Same as Opt.zip, but with one more optional.

    Type Parameters

    • X

    • Y

    Parameters

    Returns Opt<[T, X, Y]>

    Example

    some(1).zip3(some('a'), some(false)) // Some([1, 'a', false])
    none.zip3(some(1), some(2)) // None

    See

    zip3

  • Same as Opt.zip3, but with one more optional.

    Type Parameters

    • X

    • Y

    • Z

    Parameters

    Returns Opt<[T, X, Y, Z]>

    See

    zip4

  • Same as Opt.zip4, but with one more optional.

    Type Parameters

    • X

    • Y

    • Z

    • ZZ

    Parameters

    Returns Opt<[T, X, Y, Z, ZZ]>

    See

    zip5

  • Zips each element of an array inside the Opt with the corresponding element from another array. If the arrays are of different lengths, the resulting array will have the length of the shorter one.

    Type Parameters

    • U

    • V

    Parameters

    Returns Opt<readonly [U, V][]>

    Example

    opt([1, 2]).zipIn([3, 4]) // Some([[1, 3], [2, 4]])
    opt([1, 2]).zipIn(null) // None
    none.zipIn([1, 2]) // None
  • Returns Some with same value if predicate holds, None otherwise.

    Parameters

    • predicate: ((_) => boolean)
        • (_): boolean
        • Parameters

          • _: T

          Returns boolean

    Returns Opt<T>

    Example

    opt(1).filter(x => x > 0); // Some(1)
    opt(-1).filter(x => x > 0); // None

    See

  • Filters each element of an array inside the Opt, returning an Opt of the array with elements that pass the test implemented by the provided function.

    Type Parameters

    • U

    Parameters

    • this: Opt<U[]>
    • f: ((x) => boolean)
        • (x): boolean
        • Parameters

          • x: U

          Returns boolean

    Returns Opt<U[]>

    Example

    opt([1, 2, 3]).filterIn(x => x > 1) // Some([2, 3])
    
  • Filter by regular expression. It is a shortcut function for Opt.filter + testRe.

    Type Parameters

    • R extends Opt<string>

    Parameters

    • regex: RegExp

    Returns R

    Example

    opt('Luffy').filterByRe(/f+/) // Some('Luffy')
    opt('Robin').filterByRe(/f+/) // None
  • Searches for an element within an array inside the Opt instance that matches the given predicate.

    This method will return a new Opt containing the first element that satisfies the predicate function. If the Opt instance is None or the value inside is not an array, it will return None.

    Type Parameters

    • U

      The type of elements in the array.

    Parameters

    • this: Opt<U[]>

      The Opt instance containing an array.

    • f: ((x) => boolean)

      A predicate function to test each element.

        • (x): boolean
        • Parameters

          • x: U

          Returns boolean

    Returns Opt<U>

    A new Opt containing the found element or None if no element matches the predicate or if the Opt is None.

    Example

    opt([1, 2, 3, 4]).findIn(x => x > 2) // Some(3)
    opt([1, 2, 3, 4]).findIn(x => x > 5) // None
    none.findIn(x => x > 2) // None
  • Returns None if predicate holds, otherwise passes same instance of Opt.

    Parameters

    • predicate: ((_) => boolean)
        • (_): boolean
        • Parameters

          • _: T

          Returns boolean

    Returns Opt<T>

    Example

    opt(1).noneIf(x => x > 0); // None
    opt(-1).noneIf(x => x > 0); // Some(-1)

    See

    filter

  • Returns None when given true, otherwise passes opt unchanged.

    Parameters

    • returnNone: boolean

    Returns Opt<T>

    Example

    opt(1).noneWhen(false) // Some(1)
    opt(1).noneWhen(true) // None
  • Returns 0 or 1 for Some depending on whether the predicate holds. Returns 0 for None.

    It is a combination of Opt.filter and Opt.length.

    Parameters

    • predicate: ((_) => boolean)
        • (_): boolean
        • Parameters

          • _: T

          Returns boolean

    Returns 0 | 1

    Example

    opt('Mu').count(x => x.length > 3) // 0
    opt('Ichi').count(x => x.length > 3) // 1

    See

    count

  • Counts the number of elements in the array inside the Opt that satisfy the predicate.

    Type Parameters

    • U

    Parameters

    • this: Opt<U[]>
    • f: ((x) => boolean)

      The predicate function to test each element.

        • (x): boolean
        • Parameters

          • x: U

          Returns boolean

    Returns Opt<number>

    An Opt containing the count of elements that satisfy the predicate, or None if the Opt is None.

    Example

    opt([1, 2, 3]).countIn(x => x > 1) // Some(2)
    opt([]).countIn(x => x > 1) // Some(0)
    none.countIn(x => x > 1) // None
  • Narrows type inside Opt using given type guard.

    Type Parameters

    • U

    Parameters

    • guard: ((value) => value is U)
        • (value): value is U
        • Parameters

          • value: any

          Returns value is U

    Returns Opt<U>

    Example

    some('1' as string | number).narrow(isString) // Some('1'): Opt<string>
    some(1 as string | number).narrow(isString) // None: Opt<string>

    See

    narrow

  • Similar to Opt.narrow, but crashes on a narrowing failure.

    Type Parameters

    • U

    Parameters

    • guard: ((value) => value is U)
        • (value): value is U
        • Parameters

          • value: any

          Returns value is U

    • Optional errorFactory: (() => unknown)
        • (): unknown
        • Returns unknown

    Returns Opt<U>

  • Type Parameters

    • U

    Parameters

    • guard: ((value) => value is U)
        • (value): value is U
        • Parameters

          • value: any

          Returns value is U

    • Optional crashMessage: string

    Returns Opt<U>

  • Print value to console.

    Parameters

    • Optional tag: string

    Returns Opt<T>

    Example

    opt(1).print() // logs 'Some:', '1'; returns Some(1)
    opt(1).print('test') // logs '[test]', 'Some:', '1'; returns Some(1)
    none.print('x') // logs '[x]', 'None'; returns None

    See

    print

  • Is a value of this instance and given other instance the same? Default comparator function is === (referential equality).

    Parameters

    Returns boolean

    Example

    none.equals(none) // true
    some(1).equals(none) // false
    some(1).equals(some(1)) // true
    some(1).equals(some(2)) // false
    some({a: 1}).equals(some({a: 1})) // false (different objects)
    some(1).equals(some(2), (x, y) => true) // true (custom comparator function)

    const jsonCmp = <T>(a: T, b: T): boolean => JSON.stringify(a) === JSON.stringify(b);
    some({a: 1}).equals(some({a: 1}), jsonCmp) // true (comparing values converted to JSON)

    See

    equals

  • Experimental

    Widen union (typically union of strings to string).

    May be removed if it is later found out it's unsafe and unfixable.

    Type Parameters

    Returns Opt<R>

    Example

    type EnumAB = 'a' | 'b';
    type EnumABC = 'a' | 'b' | 'c';
    const ab = 'a' as EnumAB;
    const abc = 'c' as EnumABC;
    const correctWiden: Opt<EnumABC> = opt(ab).widen<EnumABC>(); // AB -> ABC: Ok
    const wrongWiden: Opt<never> = opt(abc).widen<EnumAB>(); // ABC -> AB: Not Ok, C is not in AB
  • Maps property of a wrapped object.

    Type Parameters

    • K extends string | number | symbol

    Parameters

    • key: K

    Returns OptSafe<T[K]>

    Example

    const a = {x: 1};
    const xValue = opt(a).prop('x').orCrash('missing prop x'); // 1

    See

  • Get a field from a wrapped object. Crash if the field is missing or empty, or opt instance is None. Shortcut of Opt.prop + Opt.orCrash.

    Type Parameters

    • K extends string | number | symbol

    • R extends {}

    Parameters

    • key: K
    • Optional errorFactory: string | ((key) => string | Error)

    Returns R

    Example

    interface A {x?: number;}

    const aFull: A = {x: 4};
    opt(aFull).propOrCrash('x'); // 4

    const aEmpty: A = {};
    opt(aEmpty).propOrCrash('x'); // crash

    // with custom error: "Custom error: x is missing"
    opt(aEmpty).propOrCrash('x', 'Custom error: x is missing'); // crash
    opt(aEmpty).propOrCrash('x', key => `Custom error: ${key} is missing`); // crash
    opt(aEmpty).propOrCrash('x', key => new Error(`Custom error: ${key} is missing`)); // crash
  • Get a field from a wrapped object. Return null if the field is missing or empty, or opt instance is None.

    Type Parameters

    • K extends string | number | symbol

    • R extends null | {}

    Parameters

    • key: K

    Returns R

    Example

    interface A {x?: number;}

    const aFull: A = {x: 4};
    opt(aFull).propOrNull('x'); // 4

    const aEmpty: A = {};
    opt(aEmpty).propOrNull('x'); // null
  • Get a field from a wrapped object. Return undefined if the field is missing or empty, or opt instance is None.

    Type Parameters

    • K extends string | number | symbol

    • R extends undefined | {}

    Parameters

    • key: K

    Returns R

    Example

    interface A {x?: number;}

    const aFull: A = {x: 4};
    opt(aFull).propOrUndef('x'); // 4

    const aEmpty: A = {};
    opt(aEmpty).propOrUndef('x'); // undefined
  • Get a field from a wrapped object. Return 0 if the field is missing or empty, or opt instance is None.

    Type Parameters

    • K extends string | number | symbol

    • R extends {} | 0

    Parameters

    • key: K

    Returns R

    Example

    interface A {x?: number;}

    const aFull: A = {x: 4};
    opt(aFull).propOrZero('x'); // 4

    const aEmpty: A = {};
    opt(aEmpty).propOrZero('x'); // 0
  • Generates property getters for an Opt instance.

    Type Parameters

    • U extends object

    • K extends string | number | symbol

    Parameters

    • this: Opt<U>
    • Optional errorFactoryGeneric: string | ((key) => string | Error)

    Returns NakedPropGetters<U, K>

    An object with property getter methods

    Example

    interface Obj { x: number; y: string; z?: number; }
    const obj = opt<Obj>({ x: 1, y: 'hello' });
    const getters = obj.genPropGetters();
    getters.orCrash('x') // 1
    getters.orNull('y') // 'hello'
    getters.orUndef('z') // undefined
    getters.orZero('x') // 1

    // with custom error
    const gettersWithCustomError = obj.genPropGetters(key => `Custom error: ${key} is missing`);
    gettersWithCustomError.orCrash('z') // crashes with 'Custom error: z is missing'
    gettersWithCustomError.orCrash('z', 'nope, no z') // crashes with 'nope, no z'
  • Swaps value inside (for None it's noop).

    Type Parameters

    • U

    Parameters

    • newValue: U

    Returns Opt<U>

    Example

    opt(1).swap('a') // Some('a')
    none.swap('a') // None

    Same as map(const(newValue)).

    See

    swap

  • Get an item at given index of an array/string wrapped in Opt. Resulting value is wrapped in Opt. Non-existent index results in None. Negative index is interpreted as an index from the end of the array (e.g. a last item of an array lies on an index equal to -1).

    Type Parameters

    • R extends unknown

    Parameters

    • index: number

    Returns OptSafe<R>

    Example

    opt([1]).at(0) // Some(1)
    opt([]).at(0) // None
    none.at(0) // None
    opt([null]).at(0) // None
    opt([1, 2, 3]).at(-1) // Some(3)
    opt('Palico').at(0) // Some('P')

    See

    at

  • Get a first item of an array or a first character of a string wrapped in Opt.

    Type Parameters

    • R extends unknown

    Returns OptSafe<R>

    Example

    opt([1, 2, 3]).headIn() // Some(1)
    opt([]).headIn() // None
    opt(null).headIn() // None
    opt('Palico').headIn() // Some('P')

    See

    head

  • Get minimum from an array.

    Type Parameters

    • R extends unknown

    Returns OptSafe<R>

    Example

    opt([5, 1, 3]).minIn() // Some(1)
    none.minIn() // None
    opt([]).minIn() // None
  • Get maximum from an array.

    Type Parameters

    • R extends unknown

    Returns OptSafe<R>

    Example

    opt([3, 7]).maxIn() // Some(7)
    none.maxIn() // None
    opt([]).maxIn() // None
  • Get a last item of an array or a last character of a string.

    Type Parameters

    • R extends unknown

    Returns OptSafe<R>

    Example

    opt([1, 2, 3]).lastIn() // Some(3)
    opt([]).lastIn() // None
    opt(null).lastIn() // None
    opt('Palico').lastIn() // Some('o')

    See

    last

  • A convenience function to test this (Opt<string>) against a given regular expression.

    Type Parameters

    Parameters

    • re: RegExp

      Regular expression

    Returns R

    Example

    opt('a').testReOrFalse(/a/) // true
    opt('b').testReOrFalse(/a/) // false

    See

    testReOrFalse

  • Apply (call) a function inside Some. Does nothing for None.

    Type Parameters

    • R extends any

    • A extends any[]

    Parameters

    • Rest ...args: A

      Parameters passed to wrapped function.

    Returns Opt<R>

    opt-wrapped result from the function

    Example

    const add = (a: number, b: number) => a + b;
    opt(add).apply(2, 3) // Some(5)
    none.apply(0) // None

    Example

    It can also be used with curried functions.

    const sub = (a: number) => (b: number) => a - b;
    opt(sub).apply(10).apply(3) // Some(7)

    Note

    Opt.apply is only available for functions, otherwise an exception will be thrown when called on Some.

    See

    Opt.onFunc for imperative version

  • Apply (call) a function inside Some. Does nothing for None.

    Type Parameters

    • A extends any[]

    Parameters

    • Rest ...args: A

    Returns Opt<T>

    Unchanged Opt instance

    Example

    Both lines do the same thing

    opt(f).onSome(x => x())
    opt(f).onFunc()

    Example

    const g = (a: number, b: number): void => console.log(a, b);
    opt(g).onFunc(1, 2) // calls `g` (prints 1 and 2), returns Some(g)
    none.onFunc(79) // None

    Note

    onFunc is only available for functions, otherwise an exception will be thrown when called on Some.

    Imperative

    See

    Opt.apply for functional version

Generated using TypeDoc