title: Dynamically add function declaration in TypeScript
body: <p>I'm new to TypeScript and tried to implement a auto-generated builder pattern so that I can write something along the lines of</p>
  
  <pre class="lang-js prettyprint-override"><code>class Foo {
      @buildable('inBar')
      public bar = 'Uninitialized';
  
      constructor() {}
  }
  
  const FooBuilder = getBuilder&lt;Foo&gt;(Foo);
  
  const foo = new FooBuilder().inBar('My Bar').build();
  </code></pre>
  
  <p>Writing <a href="https://gist.github.com/milgner/7c872216f1e538ad6b192d8b59447a41" rel="nofollow noreferrer">the code</a> 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. </p>
  
  <p>But of course now the transpiler complains about not knowing the <code>inBar</code> function. I could use the <code>[]</code> operator like <code>const foo = new FooBuilder()['inBar']('My Bar').build();</code> but that kind of syntax somewhat defeats the purpose of having a builder pattern in the first place, which is supposed to improve readability.</p>
  
  <p>Is there some way to dynamically add functions to a type? Maybe using the <code>reflect-metadata</code> 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.</p>