4 ms·
This is great, and a strategy I used a lot in my last code base. If you do this for statically typed JS though, you'll get either error messages or bad typing w
by coltonv 8y ago
This is great, and a strategy I used a lot in my last code base. If you do this for statically typed JS though, you'll get either error messages or bad typing with lots of `any`s and weak type checks.
Here's a great strategy to do the same thing with strong static types, like in flow and typescript:
setTextField = (name: 'name' | 'email' | 'phone') => (event: InputEvent) => {
this.setState({ user: { ...this.state.user, [name]: event.target.value } });
}
setBooleanField = (name: 'isCool') => (event: InputEvent) => {
this.setState({ user: { ...this.state.user, [name]: event.target.checked } });
}
render() {
<div>
<input type="text" onChange={ this.setTextField('email')} placeholder="Email" value={this.state.user.email} />
<input type="checkbox" onChange={ this.setBooleanField('isCool')} checked={this.state.user.isCool} />
</div>
}
More verbose than the non-typed version, but simpler than declaring a function for every field with all the goodness of strong static typing.