在 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 类来帮助我实例化 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 像在内部静态类中一样导入外部类定义。 我怎样才能做到这一点?谢谢。
错误是
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;
}
更改顺序后,