Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic object key with Typescript in React event handler

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
}
like image 342
Carl Vitullo Avatar asked Dec 05 '22 13:12

Carl Vitullo


1 Answers

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);
like image 162
Amid Avatar answered Dec 09 '22 15:12

Amid