happy-rusty
    Preparing search index...

    Function tryOption

    • Executes a function and returns Some with the result if successful, or None if it throws.

      This converts try-catch patterns to Option-based handling, where you only care about success/failure, not the error details.

      Similar to Promise.try, this function accepts optional arguments that are passed to the function.

      Type Parameters

      • T

        The type of the value returned by the function.

      • Args extends unknown[]

        The types of the arguments to pass to the function.

      Parameters

      • fn: (...args: Args) => T

        A function that may throw an exception.

      • ...args: Args

        Arguments to pass to the function.

      Returns Option<T>

      Some<T> if the function succeeds, or None if it throws.

      1.7.0

      // Parse JSON, ignore error details
      const data = tryOption(JSON.parse, jsonString);
      console.log(data.unwrapOr(defaultData));
      // Validate URL - using closure form
      const url = tryOption(() => new URL(input));
      url.inspect(u => console.log('Valid URL:', u.href));
      // Decode URI component with arguments
      const decoded = tryOption(decodeURIComponent, str);