-2
是否可以执行此答案中提供的等效项,但在Typescript中?在Typescript中扩展生成器
Subclassing a Java Builder class
这里是我迄今为止的基础类:
export class ProfileBuilder {
name: string;
withName(value: string): ProfileBuilder {
this.name= value;
return this;
}
build(): Profile{
return new Profile(this);
}
}
export class Profile {
private name: string;
constructor(builder: ProfileBuilder) {
this.name = builder.Name;
}
}
和扩展类:
export class CustomerBuilder extends ProfileBuilder {
email: string;
withEmail(value: string): ProfileBuilder {
this.email = value;
return this;
}
build(): Customer {
return new Customer(this);
}
}
export class Customer extends Profile {
private email: string;
constructor(builder: CustomerBuilder) {
super(builder);
this.email= builder.email;
}
}
像其他线程提到,我不会像能够根据上下文的变化建立客户:
let customer: Customer = new CustomerBuilder().withName('John')
.withEmail('[email protected]')
.build();
我目前正在尝试使用泛型来解决这个问题,但是我在为setter方法返回这个指针时遇到了麻烦(键入这个不能分配给类型T)。有任何想法吗?
请花一些时间来阅读的https:/ /stackoverflow.com/help/how-to-ask指南。它会帮助你获得答案。 :) – toskv
是的,我正在编辑问题的过程中给我一个具体的例子,我到目前为止。 – user2595996