在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导入外部类定义作为内部静态类。我怎么能做到这一点?谢谢。
1条答案
按热度按时间nafvub8i1#
如果代码的顺序是正确的,则错误为
Class 'CarBuilder' used before its declaration.
。如果将
CarBuilder
更改为在Car
之前声明(或者从其他文件导入),则可以使用它在改变顺序之后,
TSPlayground