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
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With