title: Typescript & ReactJS How To Dynamically Set State
body: <p>I have this interface defined as my state:</p>
  
  <pre><code>interface State {
    id: string;
    name: string;
    description: string;
    dimensionID: string;
    file: File | null;
    operator: string;
    isFormValid: boolean;
    filename: string;
  };
  </code></pre>
  
  <p>I have a simple on change handler:</p>
  
  <pre><code>  update = (event: React.FormEvent&lt;HTMLInputElement&gt;): void =&gt; {
      const { name, value } = event.currentTarget;
      this.setState({ [name]: value });
    };
  </code></pre>
  
  <p>However, this error gets thrown:</p>
  
  <pre><code>Error:(109, 19) TS2345: Argument of type '{ [x: string]: string; }' is not assignable to parameter of type 'State | Pick&lt;State, "id" | "name" | "description" | "dimensionID" | "file" | "operator" | "isFormValid" | "filename"&gt; | ((prevState: Readonly&lt;State&gt;, props: Readonly&lt;Props&gt;) =&gt; State | Pick&lt;...&gt;)'.
    Type '{ [x: string]: string; }' is not assignable to type '(prevState: Readonly&lt;State&gt;, props: Readonly&lt;Props&gt;) =&gt; State | Pick&lt;State, "id" | "name" | "description" | "dimensionID" | "file" | "operator" | "isFormValid" | "filename"&gt;'.
      Type '{ [x: string]: string; }' provides no match for the signature '(prevState: Readonly&lt;State&gt;, props: Readonly&lt;Props&gt;): State | Pick&lt;State, "id" | "name" | "description" | "dimensionID" | "file" | "operator" | "isFormValid" | "filename"&gt;'.
  </code></pre>
  
  <p>My question is: How can I set state dynamically like how my on change handler tries?
  This handler is used for different parts of the form so I won't know which key of state I will need to update.</p>
  
  <p><strong>Update: SOLUTION</strong>
  From this <a href="https://github.com/Microsoft/TypeScript/issues/13948#issuecomment-412365629" rel="noreferrer">post</a></p>
  
  <pre><code>  update = (event: React.FormEvent&lt;HTMLInputElement&gt;): void =&gt; {
      const { name, value } = event.currentTarget;
      this.setState(prevState =&gt; ({
        ...prevState,
        [name]: value,
      }))
    };
  </code></pre>
  
  <p>Works!</p>