title: How to specify generic key constraint in function argument
body: <p>I might be going about this the wrong way, I just wanted to have a little bit of fun in code today. I'm sure a library already does this as well. </p>
  
  <p>I am creating a generic <code>pushUnique</code> function that determines if a new object being pushed to an array is unique based on a key, and if so, push it.</p>
  
  <p>So far I have little more than pseudo-code that doesn't work for obvious reasons: </p>
  
  <pre><code>  pushUnique&lt;T, U&gt;(arr: T[], obj: T, key: U = null) {
      if (key !== null) {
        const index = arr.findIndex(o =&gt; o.key === obj.key);
      }
    }
  </code></pre>
  
  <p>How can I get the object name of the key and specify it for the findIndex function?</p>
  
  <hr>
  
  <p>EDIT:</p>
  
  <p>With help from Titian Cernicova-Dragomir this is my final solution for now that works great for my POC needs!</p>
  
  <pre><code>export class Utils {
    pushUnique&lt;T, U&gt;(arr: T[], obj: T, key: (o: T) =&gt; U = null, logVerbose: boolean = false): void {
      if (logVerbose === true) {
        console.log('pushUnique called');
      }
  
      if (typeof obj === 'object' &amp;&amp; key === null) {
        console.warn('Object defined in pushUnique is complex, but a key was not specified.');
      } else if (typeof obj !== 'object' &amp;&amp; key !== null) {
        console.warn('Object is not complex, but a key was specified');
      }
  
      const index = key !== null ? arr.findIndex(o =&gt; key(o) === key(obj)) : arr.indexOf(obj);
      if (index === -1) {
        arr.push(obj);
      } else {
        if (logVerbose === true) {
          console.log('Duplicate object, not added');
        }
      }
    }
  }
  </code></pre>