I am building a painter that can chain getters, but each getter can only be called once. For TextDecorator
and BgDecorator
, they are easy to handle because I can just return different classes. However, for StyleDecorator
, since it is allowed to apply multiple styles, I don’t know how to define a type that can accumulate omitted getters. Please see the code below:
class Painter {
protected textColor: string
protected bgColor: string
protected styles: string[]
paint() {
// paint the text
}
static create() {
return new TextDecorator()
}
}
class StyleDecorator extends Painter {
get bold(): Omit<StyleDecorator, 'bold'> {
this.styles.push('bold')
return this
}
get underline(): Omit<StyleDecorator, 'underline'> {
this.styles.push('underline')
return this
}
get italics(): Omit<StyleDecorator, 'italics'> {
this.styles.push('italics')
return this
}
}
class BgDecorator extends StyleDecorator {
get redBg(): StyleDecorator {
this.bgColor = "red"
return this
}
get blueBg(): StyleDecorator {
this.bgColor = "blue"
return this
}
}
class TextDecorator extends BgDecorator {
get white(): BgDecorator {
this.textColor = "white"
return this
}
get black(): BgDecorator {
this.textColor = "black"
return this
}
}
Painter.create().white.redBg.bold.underline.paint() // ok
Painter.create().white.blueBg.bold.underline.bold.paint() // I want to see error that says bold cannot be called twice.
Painter.create().white.redBg.underline.bold.underline.paint() // I want to see error that says underline cannot be called twice.
Painter.create().white.redBg.italics.underline.italics.underline.paint() // I want to see error that says underline and italics cannot be called twice.
I looked at this by lukasgeiter and this by Titain they are close to what I want to achieve, but they are not getter and for me it is very difficult to understand how it works hence don’t even know how to modifi it..
Please help.