Is it possible to do the equivalent provided in this answer, but in Typescript?
Subclassing a Java Builder class
Here is what I have so far for the base 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;
}
}
And the extended class:
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;
}
}
Like the other thread mentions, I won`t be able to build a Customer in this order because of the change of context:
let customer: Customer = new CustomerBuilder().withName('John')
.withEmail('john@email.com')
.build();
I am currently trying to use generics to fix the issue, but I am having trouble when returning the this pointer for my setter methods (type this is not assignable to type T). Any ideas?