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
}