@binarymuse/ts-stdlib
    Preparing search index...

    Function Ok

    • Creates a new Ok result.

      Type Parameters

      • T

        The type of the success value

      • E = never

        The type of the error value

      Parameters

      • value: T

      Returns Result<T, E>

    Index

    result

    result

    • Converts a Promise<T> into a Result<T, E>. Note that if the promise rejects, an Err<E> with the rejected value will be returned, even if the rejected value is not of type E.

      For type-safe error handling, use mapErr to transform and validate errors:

      Type Parameters

      • T

        The type of the success value

      • E = unknown

        The type of the error value; defaults to unknown

      Parameters

      • promise: Promise<T>

        The promise to convert.

      Returns Promise<Result<Awaited<T>, E>>

      A Result<T, E> that resolves to the value of the promise if it resolves, or an Err if it rejects.

      // Basic usage
      const result = await Ok.from(Promise.resolve(42));
      console.log(result.unwrap()); // 42

      // Error handling with mapErr;
      // `result` is of type `Result<Response, NetworkError | UnknownError>`
      const result = (await Ok.from(fetch('/api/users')))
      .mapErr((error: unknown) => {
      if (error instanceof TypeError) {
      return new NetworkError('Network request failed', { cause: error });
      }
      return new UnknownError('Unknown error occurred', { cause: error });
      });

      // Handling specific error types;
      // `result` is of type `Result<DatabaseResponse, DuplicateEntryError | TableNotFoundError | DatabaseError | UnknownError>`
      const result = (await Ok.from(databaseQuery()))
      .mapErr((error: unknown) => {
      if (error instanceof DatabaseError) {
      switch (error.code) {
      case 'ER_DUP_ENTRY':
      return new DuplicateEntryError('Record already exists');
      case 'ER_NO_SUCH_TABLE':
      return new TableNotFoundError('Table does not exist');
      default:
      return new DatabaseError('Database operation failed', { cause: error });
      }
      }
      return new UnknownError('Unexpected error', { cause: error });
      });

      // Handling AggregateError from Promise.allSettled;
      // `results` is of type `Result<PromiseSettledResult<number>[], ValidationError | UnknownError>`
      const results = await Ok.from(Promise.allSettled([promise1, promise2]))
      .mapErr((error: unknown) => {
      if (error instanceof AggregateError) {
      return new ValidationError('Multiple errors occurred', error.errors);
      }
      return new UnknownError('Unexpected error', { cause: error });
      });

      // Handling AbortError;
      // `result` is of type `Result<Response, CancelledError | NetworkError>`
      const result = await Ok.from(fetch(url, { signal: abortController.signal }))
      .mapErr((error: unknown) => {
      if (error instanceof AbortError) {
      return new CancelledError('Request was cancelled');
      }
      return new NetworkError('Network request failed', { cause: error });
      });
    • Executes a function that might throw and returns a Result containing the return value or the thrown error.

      Note: TypeScript cannot automatically infer the error types from functions. You may need to provide explicit type annotations for better type safety.

      Type Parameters

      • T

        The type of the return value

      • E = unknown

        The type of the error; defaults to unknown

      Parameters

      • fn: () => T

        A function that might throw an error.

      Returns Result<T, E>

      A Result containing the return value or the thrown error.

      const result = Ok.try(() => {
      if (Math.random() > 0.5) throw new Error('Random failure');
      return 42;
      });