← 中文资源

简体中文版本

类型安全建造者模式

建造者在其类型中累积必填字段,未提供所有必需值前无法通过编译调用 build。

阅读英文原文

实现说明

RequestBuilder承载全部实现。 返回值是携带 url 的对象。

使用要点

  • 值得导入的表面是 RequestBuilder;周围的辅助代码对片段是私有的。

常见问题

RequestBuilder 会修改传入的参数吗?

不会。传入的任何东西都不会被写入,对共享数据调用是安全的。

复制和运行之间有安装步骤吗?

没有。从复制到运行之间没有别的要做。

核心语句

return this as unknown as RequestBuilder<true, HasMethod>;
return this as unknown as RequestBuilder<HasUrl, true>;
return { url: this.url, method: this.method };

代码示例

export class RequestBuilder<HasUrl extends boolean, HasMethod extends boolean> {
  private url = "";
  private method = "GET";
  private headers: Record<string, string> = {};

  static create(): RequestBuilder<false, false> {
    return new RequestBuilder<false, false>();
  }

  withUrl(this: RequestBuilder<false, HasMethod>, url: string): RequestBuilder<true, HasMethod> {
    this.url = url;
    return this as unknown as RequestBuilder<true, HasMethod>;
  }

  withMethod(this: RequestBuilder<HasUrl, false>, method: string): RequestBuilder<HasUrl, true> {
    this.method = method;
    return this as unknown as RequestBuilder<HasUrl, true>;
  }

  withHeader(key: string, value: string): this {
    this.headers[key] = value;
    return this;
  }

  build(this: RequestBuilder<true, true>): { url: string; method: string } {
    return { url: this.url, method: this.method };
  }
}