TS builder pattern
TS strict builder class
interface SomeInterface {
a: string
b: number
c: boolean
}
export class Builder<T extends Partial<SomeInterface>> {
readonly #current: T
static create<T extends Partial<SomeInterface>>(init: T) {
return new Builder({ ...init })
}
constructor(init: T) {
this.#current = init
}
setA(value: string) {
return new Builder({ ...this.#current, a: value })
}
setB(value: number) {
return new Builder({ ...this.#current, b: value })
}
setC(value: boolean) {
return new Builder({ ...this.#current, c: value })
}
build(this: Builder<SomeInterface>): SomeInterface {
return {
a: this.#current.a,
b: this.#current.b,
c: this.#current.c
}
}
}
const typedObject = Builder.create({ a: 'a' }).setB(666).setC(true).build()