title: Typescript dynamic class methods
body: <h2>Problem</h2>
  
  <p>How can one add type checking to a dynamically created class method?</p>
  
  <h2>Example</h2>
  
  <p>Given a very simple <code>Property</code> class.</p>
  
  <pre><code>class Property {
    value: any;
    name: string;
  
    constructor(name: string, value: any) {
      this.name = name;
      this.value = value
    }
  }
  </code></pre>
  
  <p>and an <code>Entity</code> class </p>
  
  <pre><code>class Entity {
    name: string;
    properties: Property[];
  
  
    constructor(name: string, properties: Property[]) {
      this.name = name;
      this.properties = properties;
  
      this.properties.forEach((p: Property, index: number) =&gt; {
        this[p.name] = (value: string): any =&gt; {
          if (value) {
            this.properties[index].value = value;
          }
          return this.properties[index].value;
        }
      }, this);
    }
  }
  </code></pre>
  
  <p>Important part: <code>this[p.name] = function ...</code>  (we don't know the name of the method at "transpile" time).</p>
  
  <p>We get the following error when transpiling to javascript:</p>
  
  <pre><code>var car = new domain.Entity(
    'car',
    [
      new domain.Property('manufacturer', 'Ford'),
      new domain.Property('model', 'Focus')
    ]
  );
  
  car.model() // error TS2339: Property 'model' does not exist on type 'Entity'.
  </code></pre>
  
  <p>I know that this is a uncommon use of classes as different instances of <code>Entity</code> will have different methods defined. Is there a way to get rid of the error, i.e. <strong>typescript is able to identify the proper interface per instance</strong>, or at least <strong>silent the error</strong>?</p>
  
  <h2>Notes</h2>
  
  <p>This is valid javascript and one could use it in the following manner:</p>
  
  <pre><code>var car = new domain.Entity(
    'car',
    [
      new domain.Property('manufacturer', 'Ford'),
      new domain.Property('model', 'Focus')
    ]
  );
  
  car.model()          // 'Focus'
  car.model('Transit') // 'Transit'
  </code></pre>
  
  <p>I'm aware that this has been asked on a <a href="https://stackoverflow.com/questions/19242034/typescript-dynamic-properties-and-methods">similar question</a>, but this case is slightly different as the method name is also defined at runtime.</p>