I'm new to TypeScript and tried to implement a auto-generated builder pattern so that I can write something along the lines of
class Foo {
@buildable('inBar')
public bar = 'Uninitialized';
constructor() {}
}
const FooBuilder = getBuilder<Foo>(Foo);
const foo = new FooBuilder().inBar('My Bar').build();
Writing the code for this was more or less straightforward, considering that not only am I new to TS but also been away from JS for some time.
But of course now the transpiler complains about not knowing the inBar
function. I could use the []
operator like const foo = new FooBuilder()['inBar']('My Bar').build();
but that kind of syntax somewhat defeats the purpose of having a builder pattern in the first place, which is supposed to improve readability.
Is there some way to dynamically add functions to a type? Maybe using the reflect-metadata
API?
I'm aware that decorators are not supposed to add methods to the decorated class but in this case I'm trying to dynamically create a new class in order to avoid having to write and maintain all the boilerplate code associated with the builder class. Being able to dynamically add a type declaration would be quite useful here.