You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript实现带回调的链式Result类如何支持返回值传递

实现方案

你需要调整三个链式方法的类型定义、入参规则和返回值处理逻辑,核心是支持回调接收上游结果、自动封装回调返回值、透传失败状态。

完整修改后代码

export class Result<T> {
  success: boolean;
  private error: string | null;
  private _value: T;

  get value(): T {
    if (!this.success) {
      throw new Error('Cannot get value of an error result.');
    }
    return this._value;
  }

  get errorMessage(): string {
    if (this.success || this.error === null) {
      throw new Error('Cannot get error message of a success result.');
    }
    return this.error;
  }

  get failure(): boolean {
    return !this.success;
  }

  private constructor(success: boolean, error: string | null, value?: T) {
    if (success && error != null) {
      throw new Error('Success result cannot have error message');
    }
    if (!success && (error === null || error.length === 0)) {
      throw new Error('Failed result must have error message');
    }
    this.success = success;
    this.error = error;
    this._value = value as T;
  }

  /**
   * Create failure result
   * @param errorMessage error message
   * @returns failureResult
   */
  static fail<T>(errorMessage: string): Result<T> {
    return new Result(false, errorMessage);
  }

  /**
   * Create success result
   * @param value
   * @returns successResult
   */
  static ok<T>(value?: T): Result<T> {
    return new Result(true, null, value);
  }

  /**
   * Combine multiple results into one result
   * @param results
   * @returns result
   */
  static combine(...results: Result<any>[]): Result<any> {
    for (let result of results) {
      if (result.failure) {
        return result;
      }
    }
    return Result.ok();
  }

  /**
   * Execute callback when result is success, pass current value to callback, return new result for chain
   * @param func Callback that receives current value, can return plain value or another Result
   * @returns New result from callback, or current failure result
   */
  onSuccess<U>(func: (value: T) => U | Result<U>): Result<U> {
    if (this.failure) {
      // 失败状态直接透传,不执行回调
      return this as unknown as Result<U>;
    }
    try {
      const callbackResult = func(this.value);
      // 回调返回的是Result实例直接透传,否则包装为成功结果
      return callbackResult instanceof Result ? callbackResult : Result.ok(callbackResult);
    } catch (e) {
      // 回调抛出异常自动转为失败结果
      return Result.fail((e as Error).message);
    }
  }

  /**
   * Execute callback when result is failure, pass error message to callback, return new result for chain
   * @param func Callback that receives error message, can return plain value or another Result
   * @returns New result from callback, or current success result
   */
  onFailure<U>(func: (error: string) => U | Result<U>): Result<T | U> {
    if (this.success) {
      // 成功状态直接透传,不执行回调
      return this;
    }
    try {
      const callbackResult = func(this.errorMessage);
      return callbackResult instanceof Result ? callbackResult : Result.ok(callbackResult);
    } catch (e) {
      return Result.fail((e as Error).message);
    }
  }

  /**
   * Execute callback regardless of result status, pass current result instance to callback, return new result for chain
   * @param func Callback that receives current Result instance, can return plain value or another Result
   * @returns New result from callback
   */
  onBoth<U>(func: (result: Result<T>) => U | Result<U>): Result<U> {
    try {
      const callbackResult = func(this);
      return callbackResult instanceof Result ? callbackResult : Result.ok(callbackResult);
    } catch (e) {
      return Result.fail((e as Error).message);
    }
  }
}

关键修改说明

  • 三个方法都增加了泛型U支持,适配链式调用过程中返回值类型变化的场景
  • 回调入参增加了对应上下文:onSuccess接收当前成功结果的value,onFailure接收当前错误信息,onBoth接收完整的Result实例
  • 自动处理回调返回值:如果回调返回Result实例直接透传,普通值自动包装为Result.ok,回调抛出的异常自动转为Result.fail
  • 失败状态下onSuccess直接透传失败结果,不会执行后续成功回调,符合面向铁路编程的设计逻辑

使用示例

和你参考的C#示例用法完全对齐:

return Result.combine(billingInfoResult, customerNameResult)
  .onSuccess(() => _paymentGateway.chargeCommission(billingInfoResult.value))
  .onSuccess(() => new Customer(customerNameResult.value))
  .onSuccess(
    customer => _repository.save(customer)
      .onFailure(() => _paymentGateway.rollbackLastTransaction())
  )
  .onSuccess(() => _emailSender.sendGreetings(customerNameResult.value))
  .onBoth(result => Log(result))
  .onBoth(result => CreateResponseMessage(result));

内容的提问来源于stack exchange,提问作者Ngọc Nguyễn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 14:45:04