I have a builder class that implements an interface which it is expected to build.
However, I would like to enforce one method of this class to be called at compile time, rather than runtime. The class is designed to be used as a chain of method calls and then passed to a function as the interface it implements. It would be ideal to require the method call immediately after the constructor, but not absolutely necessary.
For example: playground
interface ISmth {
x: number;
y?: string[];
z?: string[];
}
class SmthBuilder implements ISmth {
x: number;
y?: string[];
z?: string[];
constructor(x: number) {
this.x = x;
}
useY(y: string) {
(this.y = this.y || []).push(y)
return this
}
useZ(z: string) {
(this.z = this.z || []).push(z)
return this
}
}
declare function f(smth: ISmth): void
f(new SmthBuilder(123)
.useY("abc") // make this call required
.useZ("xyz")
.useZ("qwe")
)