typesafe-ts API Documentation - v1.5.1
    Preparing search index...

    Variable resultConst

    result: {
        ok: <ResultType, ErrorType extends Error = Error>(
            value: ResultType,
        ) => Result<ResultType, ErrorType>;
        error: <ResultType, ErrorType extends Error = Error>(
            error: ErrorType,
        ) => Result<ResultType, ErrorType>;
        try: {
            <T>(fn: () => T): Result<T, Error>;
            <T, ErrorType extends Error>(
                fn: () => T,
                errorMapper: (error: unknown) => ErrorType,
            ): Result<T, ErrorType>;
        };
        try_async: {
            <T>(fn: () => Promise<T>): AsyncResult<T, Error>;
            <T, ErrorType extends Error>(
                fn: () => Promise<T>,
                errorMapper: (error: unknown) => ErrorType,
            ): AsyncResult<T, ErrorType>;
        };
        retry: <ValueType, ErrorType extends Error>(
            fn: () => Result<ValueType, ErrorType>,
            retries: number,
        ) => Result<ValueType, RetryError<ErrorType>>;
        retry_async: <ValueType, ErrorType extends Error>(
            fn: () => Promise<Result<ValueType, ErrorType>>,
            retries: number,
        ) => Promise<Result<ValueType, RetryError<ErrorType>>>;
    } = ...

    Type declaration

    • Readonlyok: <ResultType, ErrorType extends Error = Error>(
          value: ResultType,
      ) => Result<ResultType, ErrorType>

      Creates a successful Result containing the provided value. The value can be of any type, including null and undefined.

      const stringValue = result.ok("Hello");
      const numberValue = result.ok(42);
      const objectValue = result.ok({ name: "John", age: 30 });
      const nullValue = result.ok(null);
      const undefinedValue = result.ok(undefined);

      // All of these are Ok Results
      console.log(stringValue.is_ok()); // true
      console.log(numberValue.value_or(0)); // 42
    • Readonlyerror: <ResultType, ErrorType extends Error = Error>(
          error: ErrorType,
      ) => Result<ResultType, ErrorType>

      Creates a failed Result containing the provided error. The error must be an instance of Error or a subclass of Error.

      const basicError = result.error(new Error("Basic error"));
      const typeError = result.error<string, TypeError>(new TypeError("Wrong type"));
      const customError = result.error(new RangeError("Out of range"));

      // Explicitly typed error results
      const parseError: Result<number, Error> = result.error<number, Error>(new Error("Parse failed"));
      const validationError = result.error<User, ValidationError>(new ValidationError("Invalid data"));

      // All of these are Error Results
      console.log(basicError.is_error()); // true
      if (typeError.is_error()) {
      console.log(typeError.error.message); // "Wrong type"
      }

      // Custom error classes work too
      class ValidationError extends Error {
      field: string;
      constructor(message: string, field: string) {
      super(message);
      this.name = "ValidationError";
      this.field = field;
      }
      }
    • Readonlytry: {
          <T>(fn: () => T): Result<T, Error>;
          <T, ErrorType extends Error>(
              fn: () => T,
              errorMapper: (error: unknown) => ErrorType,
          ): Result<T, ErrorType>;
      }
    • Readonlytry_async: {
          <T>(fn: () => Promise<T>): AsyncResult<T, Error>;
          <T, ErrorType extends Error>(
              fn: () => Promise<T>,
              errorMapper: (error: unknown) => ErrorType,
          ): AsyncResult<T, ErrorType>;
      }
    • Readonlyretry: <ValueType, ErrorType extends Error>(
          fn: () => Result<ValueType, ErrorType>,
          retries: number,
      ) => Result<ValueType, RetryError<ErrorType>>

      Retries a result-returning function until it succeeds or has failed for all of the requested retries. If the function returns an Ok Result, the retry operation stops and returns that successful Result. If the function returns an Error Result, it's retried up to the specified number of times. If all retries fail, returns an Error Result containing all the accumulated errors.

      let attempts = 0;
      function unreliableOperation(): Result<string, Error> {
      attempts++;
      if (attempts < 3) {
      return result.error(new Error(`Attempt ${attempts} failed`));
      }
      return result.ok("Success!");
      }

      const retryResult = result.retry(unreliableOperation, 5);
      if (retryResult.is_ok()) {
      console.log(retryResult.value); // "Success!"
      }

      // Network request example
      function fetchData(): Result<string, Error> {
      // Simulated network request that might fail
      return Math.random() > 0.7
      ? result.ok("Data fetched successfully")
      : result.error(new Error("Network timeout"));
      }

      const networkResult = result.retry(fetchData, 3);
      networkResult.match({
      on_ok: (data) => console.log("Got data:", data),
      on_error: (error) => console.log("All retries failed:", error.errors.map(e => e.message))
      });

      // Can be chained with other Result operations
      const processedResult = result.retry(fetchData, 3)
      .map(data => data.toUpperCase())
      .and_then(data => data.includes("SUCCESS") ? result.ok(data) : result.error(new Error("Invalid data")));
    • Readonlyretry_async: <ValueType, ErrorType extends Error>(
          fn: () => Promise<Result<ValueType, ErrorType>>,
          retries: number,
      ) => Promise<Result<ValueType, RetryError<ErrorType>>>

      Retries a Promise returning function until it succeeds or has failed for all of the requested retries. If the function returns a Promise that resolves to an Ok Result, the retry operation stops and returns that successful Result. If the function returns a Promise that resolves to an Error Result, it's retried up to the specified number of times. If all retries fail, returns a Promise that resolves to an Error Result containing all the accumulated errors.

      let attempts = 0;
      async function unreliableAsyncOperation(): Promise<Result<string, Error>> {
      attempts++;
      await new Promise(resolve => setTimeout(resolve, 100)); // Simulate async work
      if (attempts < 3) {
      return result.error(new Error(`Async attempt ${attempts} failed`));
      }
      return result.ok("Async success!");
      }

      const retryResult = await result.retry_async(unreliableAsyncOperation, 5);
      if (retryResult.is_ok()) {
      console.log(retryResult.value); // "Async success!"
      }

      // Network request example
      async function fetchDataAsync(): Promise<Result<string, Error>> {
      return result.try_async(async () => {
      const response = await fetch('/api/data');
      if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
      }
      const data = await response.text();
      return result.ok(data);
      })
      }

      const networkResult = await result.retry_async(fetchDataAsync, 3);
      networkResult.match({
      on_ok: (data) => console.log("Got data:", data),
      on_error: (error) => console.log("All retries failed:", error.errors.map(e => e.message))
      });

      // Can be chained with other Result operations
      const processedResult = await result.retry_async(fetchDataAsync, 3)
      .then(res => res.map(data => data.toUpperCase()))
      .then(res => res.and_then(data =>
      data.includes("SUCCESS") ? result.ok(data) : result.error(new Error("Invalid data"))
      ));