2 years ago
#30428

Shivanshu
Inner static Class object is being returned as anonymous
I have written builder design pattern implementation using inner static class in typeScript.
export class BioData {
private name: string | undefined;
private age: number | undefined;
private section: string | undefined;
static Builder = class {
protected name: string | undefined;
protected age: number | undefined;
protected section: string | undefined;
setName(name: string): this {
this.name = name;
return this;
}
setAge(age: number): this {
this.age = age;
return this;
}
setSection(section: string): this {
this.section = section;
return this;
}
populate(instance: BioData): void {
instance.setName(this.name);
instance.setAge(this.age);
instance.setSection(this.section);
}
build(): BioData {
const instance = new BioData();
this.populate(instance);
return instance;
}
};
constructor(public builder?: typeof BioData.Builder) {}
setName(name: string | undefined) {
this.name = name;
}
setAge(age: number | undefined) {
this.age = age;
}
setSection(section: string | undefined) {
this.section = section;
}
}
when i'm trying to create the object in below way.
const bioDataBuilder = new BioData.Builder();
const bioData: BioData = bioDataBuilder.setName("Shivanshu").setAge(15).secSection("A").build();
here the type returned by bioDataBuilder.setName("Shivanshu")
is anonymous type(No name). but it should be BioData.Builder
. So when i'm trying to call setAge(15)
method on object returned by setName("Shivanshu")
, this is calling setMethod of BioData class
. which is actually wrong.
Can some one please help why the typeReturned by setName("Shivanshu")
is anonymous type
, although i'm returning this
from setName method defined in Inner Static class. How can i make it to returning BioData.Builder.
Thanks.
typescript
builder
react-typescript
0 Answers
Your Answer