@alanscodelog/utils
    Preparing search index...

    Function Ok

    • Barebones result monad.

      import { type Result, Ok, Err } from "@alanscodelog/utils"

      // or import * as Result from "@alanscodelog/utils/Result.js"
      // to be able to do Result.Ok and Result.Err
      // but you'll have to use Result.Result or Result.Type for the type

      function compute(x?: string): Result<string, Error> {
      return x
      ? Ok(x)
      // error automatically constructed from string.
      : Err("Oh no! Something went wrong.")
      }

      const res = compute("a")

      if (res.isOk) {
      const value = res.value // string
      const error = res.error // error! property doesn't exist
      } else {
      const value = res.value // error! property doesn't exist
      const error = res.error // error instance
      }

      const value = Ok("value").unwrap() // "value"
      const value = Err("Err").unwrap() // will throw

      Example with custom error, also see TypedError.


      const ERROR_ENUM = {
      ERROR_A: "ERROR_A",
      ERROR_B: "ERROR_B",
      }

      const ERROR_ENUM_TYPE = typeof ERROR_ENUM

      class KnownError<T extends ERROR_ENUM_TYPE = ERROR_ENUM_TYPE> extends Error {
      code:T
      constructor(
      message: string,
      code:T
      ) {
      super(message)
      this.code = code
      }
      }

      function compute(x?: string): Result<string, KnownError<ERROR_ENUM_TYPE.ERROR_A>> {
      return x
      ? Ok(x)
      : Err(new KnownError(ERROR_ENUM_TYPE.ERROR_A, "Oh no! Something went wrong")
      }

      Note that to make this properly work when a function returns multiple errors, you must pass the KnownError types as a dricriminated union for them to be distinguishable based on some property (e.g. code). For example: KnownError<TypeA> | KnownError<TypeB>, NOT KnownError<TypeA | TypeB>. You can create a helper type like this to discriminate the generic KnownError class:

      export type MultipleErrors<T extends ERROR_ENUM_TYPE> = {
      [k in T]: KnownError<k>
      }[T]

      Type Parameters

      • T = undefined

      Parameters

      • val: T = ...

      Returns Result<T, never>