在TypeScript中,有没有一种方法可以将内部构建器类驱逐到外部文件?

jvidinwx  于 2023-04-13  发布在  TypeScript
关注(0)|答案(1)|浏览(101)

在TypeScript中,我们可以创建构建器类作为我们想要构建的类的内部类。

export class Car {
  brand: string;
  year: number;

  constructor(builder: Car) {
    this.brand = builder.brand;
    this.year = builder.year;
  }

  static Builder = class {
    brand = 'Ford';
    year = 2020;

    setBrand(brand: string) {
      this.brand = brand;
      return this;
    }

    setYear(year: number) {
      this.year = year;
      return this;
    }

    build() {
      return new Car(this);
    }
  };
}

在上面的例子中,我有一个Car类,里面有一个Builder来帮助我示例化Car对象:
const car = new Car.Builder().setBrand('Fiat').setYear(2021).build();
我希望能够导出我的Builder类的定义对象类之外(即,在单独的文件),同时保持内部静态Builder的优势。
就像这样:

export class Car {
  brand: string;
  year: number;

  constructor(builder: Car) {
    this.brand = builder.brand;
    this.year = builder.year;
  }

  static Builder = CarBuilder;
}

export class CarBuilder {
   brand = 'Ford';
   year = 2020;

   setBrand(brand: string) {
     this.brand = brand;
     return this;
   }

   setYear(year: number) {
     this.year = year;
     return this;
   }

   build() {
     return new Car(this);
   }
}

唉,这不起作用,我找不到一种方法来告诉TypeScript导入外部类定义作为内部静态类。我怎么能做到这一点?谢谢。

nafvub8i

nafvub8i1#

如果代码的顺序是正确的,则错误为Class 'CarBuilder' used before its declaration.
如果将CarBuilder更改为在Car之前声明(或者从其他文件导入),则可以使用它

export class CarBuilder {
   brand = 'Ford';
   year = 2020;

   setBrand(brand: string) {
     this.brand = brand;
     return this;
   }

   setYear(year: number) {
     this.year = year;
     return this;
   }

   build() {
     return new Car(this);
   }
}

export class Car {
  brand: string;
  year: number;

  constructor(builder: Car) {
    this.brand = builder.brand;
    this.year = builder.year;
  }

  static Builder = CarBuilder;
}

在改变顺序之后,

TSPlayground

相关问题