title: typescript dynamic and safe adding element to array
body: <p>I'm porting a Javascript application to Typescript. 
  I have an object with many array properties containing data and a javscript function do access the data arrays. For simplicity I consider only the add method </p>
  
  <pre><code>function updateDataStructure(state, structureName, elem) {
     state.data[structureName].push(elem);
     return state.data[structureName];
  }
  </code></pre>
  
  <p>Porting to typescript I'd like to introduce type safety and maintain generic code.</p>
  
  <pre><code>interface AA {
      lep: string,
      snap: number,
      sul: boolean
  }
  
  interface BB {
      p1: string;
      val: number;
  }
  
  interface StateDataContainer {
      aa: AA[],
      bb: BB[],
  }
  
  class State {
      data: StateDataContainer;
  }
  
  export type DataContainerProps = keyof StateDataContainer;
  type ArrayElement&lt;ArrayType&gt; = ArrayType extends (infer ElementType)[] ? ElementType : never;
  
  function updateDataStructure&lt;K extends DataContainerProps, D extends ArrayElement&lt;StateDataContainer[K]&gt;&gt;
                  (state: State, structureName: K, elem: D)
      : StateDataContainer[K] {
  
      // @ts-ignore
      state.data[structureName].push(elem);
      return state.data[structureName];
  }
  </code></pre>
  
  <p>With this code I have a typed safe interface, the compiler checks the client code to add the proper objects into the right structure.</p>
  
  <pre><code>const state = new State();
  
  let avv: BB;
  let line: AA;
  
  let v: BB[] = updateDataStructure(state, 'bb', avv!);
  let l: AA[] = updateDataStructure(state, 'aa', line!);
  </code></pre>
  
  <p>with this solution I have to add use the  // @ts-ignore annotation in the implementation code to avoid compiler errors like:</p>
  
  <pre><code> Argument of type 'D' is not assignable to parameter of type 'AA &amp; BB'.
    Type 'ArrayElement&lt;StateDataContainer[K]&gt;' is not assignable to type 'AA &amp; BB'.
      Type '{}' is not assignable to type 'AA &amp; BB'.
        Type '{}' is not assignable to type 'AA'.
          Type 'AA | BB' is not assignable to type 'AA &amp; BB'.
  </code></pre>
  
  <p>Is there a better approach to write this code? </p>