5

Similar but distinct from How do I dynamically assign properties to an object in TypeScript?

I have a component with the state type:

{
  low: string
  high: string
}

And as is a common pattern in React, my event handler is:

handleChange = (e) => {
  let { name, value } = e.target;
  this.setState({ [name]: value });
};

With high and low as name attributes on my inputs. Typescript is erroring with:

Argument of type '{ [x: string]: string; }' is not assignable to parameter of type 'Pick<State, "low" | "high">'

Is there a way for me to tell Typescript that I only expect those 2 values? I'd like to avoid explicitly passing the key into the handler but don't want to change the state to something like:

{
  low: string
  high: string
  [key: string]: string
}
Carl Vitullo
  • 853
  • 6
  • 15

1 Answers1

15

In the perfect world we should be able to write something like this:

private handleChange = (e: {target: {name: "low" | "high", value: string}}) =>
{
    const { name, value } = e.target;

    this.setState({[name]: value});
}

But unfortunately a reported bug (see here or here) force us to use some temp workaround like casting to any or such:

this.setState({[name]: value} as any);
Amid
  • 21,508
  • 5
  • 57
  • 54