title: typescript: how to correctly type key and value parameters in Object.entries().forEach([key,value]) =>
body: <p>I got an object with specific key/value parameters and I want to iterate over it with entries() method of Object followed by a forEach() method of Array. However I do not understand how I have to type this configuration to avoiding a typescript error:</p>
  <pre><code>type objType = {
    prop1: number | undefined;
    prop2: number | undefined;
    prop3: number | undefined;
  };
  
  const obj: objType = {
    prop1: 2,
    prop2: 0,
    prop3: undefined,
  };
  
  //1st attempt
  Object.entries(obj).forEach(([key, value]) =&gt; {
    if (value === undefined || value &lt; 5) obj[key] = 5;
  });
  
  //2nd attempt
  Object.entries(obj).forEach(
    ([key, value]: [keyof objType, number | undefined]) =&gt; {
      if (value === undefined || value &lt; 5) obj[key] = 5;
    }
  );
  </code></pre>
  <p>In first attempt, I let typescript infer the type of <code>key</code> (→ <code>string</code>) and <code>value</code> (→ <code>number|undefined</code>). But in this case I got an error when doing <code>obj[key]</code> :</p>
  <blockquote>
  <p>Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'objType'. No index signature with a parameter of type 'string' was found on type 'objType'.</p>
  </blockquote>
  <p>In second attempt I forced the type of <code>key</code> to correspond to the key of <code>obj</code> using <code>keyof</code> operator, but this type definition is not allowed and I got the following message :</p>
  <blockquote>
  <p>Argument of type '([key, value]: [keyof objType, number | undefined]) =&gt; void' is not assignable to parameter of type '(value: [string, number | undefined], index: number, array: [string, number | undefined][]) =&gt; void'. Types of parameters '__0' and 'value' are incompatible.
  Type '[string, number | undefined]' is not assignable to type '[keyof objType, number | undefined]'.
  Type at position 0 in source is not compatible with type at position 0 in target.
  Type 'string' is not assignable to type 'keyof objType'.</p>
  </blockquote>
  <p>I understand the failure for first attempt but not for the second. Why TS believes that I want to assign string to the string enumeration, I'm guessing to do the opposite...?</p>
  <p>How is the correct way to type this configuration ?</p>