javascriptreactjstypescriptsetstatetypesafe

React with typescript - type safety with setState


So I've recently discovered that callbacks for event handlers are bad for rendering performance: https://reactjs.org/docs/handling-events.html

I'm trying to heed this by grabbing the properties off the event in a class method rather than doing something like: onClick={({value}) => this.setState({"someProperty" as keyof State: value})} etc.

However now that I can't explicitly declare typesafety in that callback, I'm trying to be dynamic about it and my typechecker is okay with the code below, but how can I make it complain about the input element having a name attribute that is not a keyof State?

interface State {
  someProperty: string;
}

class MakeMeSafer extends React.Component<{}, State> {

  state: State = {
    someProperty: ''
  }

  set = ({ currentTarget: { name, value } }: React.SyntheticEvent<HTMLInputElement>): void => {
    this.setState({ [name as keyof State]: value });
  }

  render(): JSX.Element {
    return (
      <div>
        <input type="text" name="some-name-not-in-state" onChange={this.set} />
      </div>
    );
  }

}

Solution

  • You are explicitly casting your name property as a key of State, so it is normal that the compiler does not complain.

    If you need type safety I would use a closure instead:

    interface State {
      someProperty: string;
    }
    
    class MakeMeSafer extends React.Component<{}, State> {
    
      state: State = {
        someProperty: ''
      }
    
      onChange = (name: keyof State) =>
        (e: React.FormEvent<HTMLInputElement>) => {
          const newValue = e.currentTarget.value;
          this.setState({name: newValue});
        }
      }
    
      render(): JSX.Element {
        return (
          <div>
            <input type="text" onChange={this.onChange('some-name-not-in-state')} />
          </div>
        );
      }
    }